Jonna
Jonna

Reputation: 1645

Entity Framework CTP 5 - Repository pattern - doing updates

How would you do an update operation with CTP 5 using DbContext and using Repository pattern? Earlier with EF 4.0, it could be done like below.

_context.Customers.AddObject(item);
_context.ObjectStateManager.ChangeObjectState(item, System.Data.EntityState.Modified);

Is there any reason as to why EF does not provide an easy way to update "disconnected" entities. I don't want to query the db and copy all the properties to the object that is returned from query. In other words, EF should have update method which takes in the entity (similar to Add method). If the entitykey already exists in the database, update the entity with the current values. i.e. why should we do "Attach" and then copy all the properties to the attached object. To me it seems redundant to copy all the properties of entities just to update when the "disconnected" object already exist.

Upvotes: 8

Views: 5088

Answers (1)

Slauma
Slauma

Reputation: 177133

I believe you can still perform the same method as in your code example to update a disconnected entity with the CTP5 DbContext:

_dbContext.Customers.Add(item);
DbEntityEntry entry = _dbContext.Entry(item);
entry.State = EntityState.Modified;

_dbContext.SaveChanges();

Looking at the generated SQL this creates of course a full update statement on all properties of the customer object including the properties that didn't actually change, since EF doesn't know what's the current state in the database. If you want to avoid that, I guess there is no other way than fetching the current state in the database before the update which could be done this way:

DbEntityEntry entry = _dbContext.Entry(_dbContext.Customers.Find(item.ID));
entry.CurrentValues.SetValues(entity);

_dbContext.SaveChanges();

(Assuming here you have a key ID on your customer object "item".)

This creates a SQL update statement which only includes the properties which indeed have changed compared to the state in the database. I'm not sure if the second way is necessarily the less performant option due to the additional select statement. If the object type is large but only very few properties have changed the overhead of sending a full update statement on all fields might be bigger than a select statement plus a "small" update statement with only the fields which are really required for the update. (But that's only speculation, I'm not a SQL Server specialist.)

Upvotes: 7

Related Questions