Entity framework objects should be updated.

entity entity-framework

Question

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?

1
24
12/14/2011 3:30:25 PM

Popular Answer

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);
28
5/31/2013 12:38:09 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow