保存更改/更新现有对象与实体框架数据集,而不必单独设置每个属性 [英] Saving changes/updating existing object in dataset with Entity FrameWork and not have to set each property individually

查看:209
本文介绍了保存更改/更新现有对象与实体框架数据集,而不必单独设置每个属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以这样做以下(不工作),而无需显式设置对象的每个属性。产品是由默认的模型粘合剂从表单提交创建的对象和ProductInDb是,我希望覆盖/更新上下文/数据库对象。产品ID主键是在两个相同的

  VAR ProductInDb = context.Products.FirstOrDefault(X => x.ProductID == product.ProductID);                    ProductInDb =产品;                    context.SaveChanges();


解决方案

您可以将现有的产品,并设置其状态为修改

如果您使用的是的DbContext API

  context.Products.Attach(产品);
context.Entry(产品).STATE = EntityState.Modified;context.SaveChanges();

有关的ObjectContext

  context.Products.Attach(产品);
context.ObjectStateManager.ChangeObjectState(产品,EntityState.Modified);context.SaveChanges();

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();

解决方案

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();

这篇关于保存更改/更新现有对象与实体框架数据集,而不必单独设置每个属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆