Entity Framework Update Single property and Validation Errors

As has already been said about how to update only one property of our model in EF.

Here I wanna go more deep in this argument:

1) attach before, modify the property after

using (var dc= new DataContext())
{
    Section s = new Section {Id = id };
    dc.Sections.Attach(s);
    s.Message = "My message";
    dc.SaveChanges();
}

2) attach before, modify the property after

using (var dc= new DataContext())
{
    Section s = new Section {Id = id, Message = "My message" };
    dc.Sections.Attach(s);
    dc.Entry(s).Property(u => u.Message).IsModified = true;
    s.Message = "My message";
    dc.SaveChanges();
}

Both solutions are great, choose what you prefer, but if our model has some required field you will get this error:

Validation failed for one or more entities. See ‘EntityValidationErrors’ property for more details. The validation errors are: The “Title” field is required.

This is why when we try to save it, EF will validate the whole entity not only the modified property.
So in my case the property Title is required on my DB.

To solve it there are 2 solution but I don’t like any of these.
I’ll show how to solve this error using the first sample.
Use fake property assignment:

using (var dc= new DataContext())
{
    // Set the required property with fake values BEFORE attach the object!
    // if you do it after attach method, EF will track the property as changed and will update also these ones
    Section s = new Section {Id = id, Title="Fake title that will not be update on DB" };
    dc.Sections.Attach(s);
    s.Message = "My message";
    dc.SaveChanges();
}

Disable Validation on save: ValidateOnSaveEnabled = false

using (var dc= new DataContext())
{
    Section s = new Section {Id = id };
    dc.Sections.Attach(s);
    s.Message = "My message";
    dc.Configuration.ValidateOnSaveEnabled = false;
    dc.SaveChanges();
    dc.Configuration.ValidateOnSaveEnabled = true;
}

If anyone know a better solution is welcome

Annunci

Informazioni su Andrea Regoli

Project Manager .Net Developer WPF WP7 Asp.Net c# javascript ajax SQL sharepoint
Questa voce è stata pubblicata in Entity Framework e contrassegnata con , , , , . Contrassegna il permalink.

Rispondi

Inserisci i tuoi dati qui sotto o clicca su un'icona per effettuare l'accesso:

Logo WordPress.com

Stai commentando usando il tuo account WordPress.com. Chiudi sessione / Modifica )

Foto Twitter

Stai commentando usando il tuo account Twitter. Chiudi sessione / Modifica )

Foto di Facebook

Stai commentando usando il tuo account Facebook. Chiudi sessione / Modifica )

Google+ photo

Stai commentando usando il tuo account Google+. Chiudi sessione / Modifica )

Connessione a %s...