简体   繁体   English

如何使用POCO和自定义ObjectContext正确更新EF4中的实体?

[英]How to correctly update entities in EF4 using POCO and custom ObjectContext?

Using the technique described here I have a simple POCO EF4 model up and running. 使用这里描述的技术我有一个简单的POCO EF4模型启动并运行。 Saving new and deleting is straightforward (using AddObject() and DeleteObject() respectively). 保存新的和删除很简单(分别使用AddObject()DeleteObject() )。 But the only way of updating objects I have found is to retrieve the stored version of the object and manually update its properties with new values from the object being saved. 但是,更新对象的唯一方法是检索对象的存储版本,并使用保存对象中的新值手动更新其属性。 Surely there is a better way? 当然有更好的方法吗?

My ObjectContext is disconnected - in otherwords, I use a new ObjectContext instance for each operation on the model. 我的ObjectContext断开连接 - 换句话说,我为模型上的每个操作使用一个新的ObjectContext实例。

Thanks. 谢谢。

Use the stub technique : 使用存根技术

public void UpdateOrder(Order o)
{
   var stub = new Order { Id = o.OrderId }; // create stub with EntityKey
   ctx.Orders.Attach(stub); // attach stub to graph
   ctx.ApplyCurrentValues("Orders", o); // override stub with values.
   ctx.SaveChanges();
}

If the entity is already in the graph, you will get an OSM exception (entity with key already exists). 如果实体已经在图中,您将获得OSM异常(具有密钥的实体已存在)。

I counteract this by checking if the object exists in the graph first (TryGetObjectStateEntry) and only attaching if it doesn't. 我通过先检查对象是否存在于图形中(TryGetObjectStateEntry)来抵消这种情况,如果不存在则仅附加。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM