Reputation: 23935
Using the technique described here I have a simple POCO 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.
Upvotes: 1
Views: 915
Reputation: 73112
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.
Upvotes: 4