使用Entity FrameWork保存更改/更新数据集中的现有对象,而不必单独设置每个属性

时间:2021-02-27 02:15:19

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.

我可以执行类似下面的操作(不起作用),而无需显式设置对象的每个属性。 Product是由表单提交中的默认模型绑定器创建的对象,而ProductInDb是我希望覆盖/更新的上下文/数据库中的对象。 ProductID主键在两者上都相同。

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

                    ProductInDb = product;

                    context.SaveChanges();

1 个解决方案

#1


13  

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

您可以附加现有产品并将其状态设置为已修改。

If you are using DbContext API

如果您使用的是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();

#1


13  

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

您可以附加现有产品并将其状态设置为已修改。

If you are using DbContext API

如果您使用的是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();