Entity framework 4 实体框架4-ApplyCurrentValues<;张力>;vs.ObjectStateManager.ChangeObjectState

Entity framework 4 实体框架4-ApplyCurrentValues<;张力>;vs.ObjectStateManager.ChangeObjectState,entity-framework-4,entity,Entity Framework 4,Entity,我们有一个带有更新方法的WCF服务,该方法更新数据库中的客户。 此方法从客户端获取分离的实体 void UpdtaeCustomer(Customer detachedCustomer); 我们想出了两种编写此方法的方法: (一) (二) Customer=context.GetObjectByKey(detachedCustomer.EntityKey); ApplyCurrentValues(“CustomerSet”,detachedCustomer); SaveChanges();

我们有一个带有更新方法的WCF服务,该方法更新数据库中的客户。 此方法从客户端获取分离的实体

void UpdtaeCustomer(Customer detachedCustomer);
我们想出了两种编写此方法的方法:

(一)

(二)

Customer=context.GetObjectByKey(detachedCustomer.EntityKey);
ApplyCurrentValues(“CustomerSet”,detachedCustomer);
SaveChanges();

我们要考虑每种方法的缺点。第一个具有一个明显的优势,即只有一次到DB的行程。但是第二种方法的优点是什么呢。(或者可能它们的行为并不完全相同)?

使用第一种方法。使用分离实体的第二种方法没有普遍的优势,相反,它会使事情变得更糟

假设您使用时间戳。时间戳是表示行版本的特殊DB类型。每次数据库中的记录更改时,时间戳都会自动增加。时间戳用于concurrecny检查,当与EF一起使用时,它作为
Computed
列处理。每次EF想要更新记录时,它都会将数据库中的时间戳与加载对象时检索到的时间戳进行比较(必须在实体中转置到客户端并返回)。如果时间戳相同,则保存记录。如果它们不同,则抛出异常


这两种方法的区别在于,第一种方法使用来自分离对象的时间戳,而第二种方法使用来自加载对象的时间戳。原因是计算列。无法在应用程序中更新计算值。

好奇:如果使用选项1,您将如何适应乐观并发?并发检查是作为单个更新查询(where子句)的一部分包含,还是强制执行新的select?@JoeBrockhaus:从数据库加载实体时,附加的实体必须具有接收到的原始时间戳。在这种情况下,它将在单个更新命令中使用其值。您好@LadislavMrnka您能看看这个问题吗?
context.CustomerSet.Attach(detachedCustomer);
context.ObjectStateManager.ChangeObjectState(detachedCustomer, entityState.Modified);
context.SaveChanges();
Customer customer = context.GetObjectByKey(detachedCustomer.EntityKey);
context.ApplyCurrentValues<Customer>("CustomerSet", detachedCustomer);
context.SaveChanges();