Entity Framework update without select part 1

To update an entity in EF6 threre are many methods.
Working with other people I noticed that unfortunately many developer don’t think what the ORM will do on DB to perform the update.
I found it also in many example on web.

So I collected all information taken from this link here.

In this post I’ll collect all available method and I analyze the pro e cons for each ones:

Method 1 – Load original record, update each property

var original = db.Users.Find(updatedUser.UserId);
if (original != null)
{
original.BusinessEntityId = updatedUser.BusinessEntityId;
original.Email = updatedUser.Email;
original.EmployeeId = updatedUser.EmployeeId;
original.Forename = updatedUser.Forename;
original.Surname = updatedUser.Surname;
original.Telephone = updatedUser.Telephone;
original.Title = updatedUser.Title;
original.Fax = updatedUser.Fax;
original.ASPNetUserId = updatedUser.ASPNetUserId;
db.SaveChanges();
}

Pros
Can specify which properties change
Views don’t need to contain every property

Cons
2 x queries on database to load original then update it

Method 2 – Load original record, set changed values

var original = db.Users.Find(updatedUser.UserId);

if (original != null)
{
db.Entry(original).CurrentValues.SetValues(updatedUser);
db.SaveChanges();
}

Pros
All properties are copied but only modified properties are sent to database

Cons
Views need to contain every property
2 x queries on database to load original then update it

Method 3 – Attach updated record and set state to EntityState.Modified

db.Users.Attach(updatedUser);
db.Entry(updatedUser).State = EntityState.Modified;
db.SaveChanges();

Pros
1 x query on database to update

Cons
Can’t specify which properties change
Views must contain every property

Method 4 – Attach and update only some properties

db.Users.Attach(updatedUser);
var entry = db.Entry(updatedUser);
entry.Property(e => e.Email).IsModified = true;
// other changed properties
db.SaveChanges();

Pros
1 x query on database to update
Can specify which properties change

If I don’t have to worry about which properties update I prefer the 3 method because I’ve to write less code. But both 3th and 4th are great, please don’t use the 1st and 2nd!!!

Annunci

Informazioni su Andrea Regoli

Project Manager .Net Developer WPF WP7 Asp.Net c# javascript ajax SQL sharepoint
Questa voce è stata pubblicata in c#, 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...