开发者

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

Using the technique described here I have a simple PO开发者_运维知识库CO EF4 model up and running. Saving new and deleting is straightforward (using AddObject() and DeleteObject() respectively). 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.

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

I counteract this by checking if the object exists in the graph first (TryGetObjectStateEntry) and only attaching if it doesn't.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜