Update entity framework objects

user75278 picture user75278 · Mar 8, 2009 · Viewed 38.1k times · Source

I transfer data between the entity framework and the business layer and user layer by using Data Transfer Objects. I do have some doubt, if I retrieve an object which is converted to a DTO, how do I update the correct object in the entity framework and not just insert a duplicate?

Answer

Rob picture Rob · Nov 18, 2010

The following code will update an EF 4 entity that has been created as a controller parameter in MVC from a strongly typed view:

It seems the trick is to use the ObjectStateManager to change the state from Added to Modified once the entity has been added to the context.

MyEntities db = new MyEntities();
db.Product.AddObject(product);
db.ObjectStateManager.ChangeObjectState(product, System.Data.EntityState.Modified);
return db.SaveChanges() > 0;

As per @Sean Mills comment if you are using EF5 use:

 ((IObjectContextAdapter) db).ObjectContext.ObjectStateManager.ChangeObjectState(entity, System.Data.EntityState.Added);