Saving changes/updating existing object in dataset with Entity FrameWork and not have to set each property individually

吃可爱长大的小学妹 提交于 2019-12-08 19:21:02

问题


Can I do something like the below (which does not work) without having to explicitly set each property of the object. Product is the object that is created by the default model binder from a form submission and ProductInDb is object in the context/database that I wish to override/update. The ProductID primary key is the same on both.

var ProductInDb = context.Products.FirstOrDefault(x => x.ProductID == product.ProductID);

                    ProductInDb = product;

                    context.SaveChanges();

回答1:


You can attach the existing product and set its state as Modified.

If you are using DbContext API

context.Products.Attach(product);
context.Entry(product).State = EntityState.Modified;

context.SaveChanges();

For ObjectContext

context.Products.Attach(product);
context.ObjectStateManager.ChangeObjectState(product, EntityState.Modified);

context.SaveChanges();


来源:https://stackoverflow.com/questions/7642570/saving-changes-updating-existing-object-in-dataset-with-entity-framework-and-not

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!