Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework 4 - ApplyCurrentValues<TEntity> vs. ObjectStateManager.ChangeObjectState

We have an WCF service with an update method that updates a Customer in the DB. This method get a detached entity from the client.

void UpdtaeCustomer(Customer detachedCustomer);

We came up with two ways to write this method :

1)

context.CustomerSet.Attach(detachedCustomer);
context.ObjectStateManager.ChangeObjectState(detachedCustomer, entityState.Modified);
context.SaveChanges();

2)

Customer customer = context.GetObjectByKey(detachedCustomer.EntityKey);
context.ApplyCurrentValues<Customer>("CustomerSet", detachedCustomer);
context.SaveChanges();

We want to consider the cons\pros of each method. The first one has a clear advantage of having only one trip to the DB. But what are the pros of the second method. (or maybe they don't act quite the same) ?

like image 953
Yaron Levi Avatar asked Apr 04 '11 22:04

Yaron Levi


1 Answers

Use the first approach. There is no general advantage in using second method with detached entity on the contrary it can make things even worse.

Suppose that you use timestamp. Timestamp is special DB type representing row version. Each time the record in database changes the timestamp is automatically increased. Timestamp is used for concurrecny checks and when using with EF it is handled as Computed column. Each time the EF wants to update the record it compares timestamp in database with the timestamp you retrieved when you loaded the object (must be transpored in your entity to client and back). If timestamps are same the record is saved. If they are different an exception is thrown.

The difference between those two methods is that first method uses timestamp from detached object whereas second method uses timestamp from loaded object. The reason is the computed column. Computed values can't be updated in the application.

like image 168
Ladislav Mrnka Avatar answered Oct 06 '22 20:10

Ladislav Mrnka