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

折月煮酒 提交于 2019-12-08 23:32:38

问题


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) ?


回答1:


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.



来源:https://stackoverflow.com/questions/5544849/entity-framework-4-applycurrentvaluestentity-vs-objectstatemanager-changeob

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!