我们有一个带有更新方法的 WCF 服务,用于更新数据库中的客户。
此方法从客户端获取一个分离的实体。
void UpdtaeCustomer(Customer detachedCustomer);
我们想出了两种方法来编写这个方法:
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();
我们要考虑每种方法的缺点\优点。第一个有一个明显的优势,即只有一次到 DB 的行程。但是第二种方法的优点是什么。 (或者他们的行为可能不太一样)?
最佳答案
使用第一种方法。对分离实体使用第二种方法没有普遍优势,相反它会使事情变得更糟。
假设您使用时间戳。时间戳是表示行版本的特殊 DB 类型。每次数据库中的记录更改时,时间戳都会自动增加。时间戳用于并发检查,当与 EF 一起使用时,它被处理为 Computed
柱子。每次 EF 想要更新记录时,它都会将数据库中的时间戳与您在加载对象时检索到的时间戳进行比较(必须在您的实体中传输到客户端并返回)。如果时间戳相同,则保存记录。如果它们不同,则抛出异常。
这两种方法之间的区别在于,第一种方法使用来自分离对象的时间戳,而第二种方法使用来自加载对象的时间戳。原因是计算列。无法在应用程序中更新计算值。
关于entity-framework-4 - Entity Framework 4 - ApplyCurrentValues<TEntity> 与 ObjectStateManager.ChangeObjectState,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5544849/