更换实体框架对象 [英] Replace Entity Framework object
问题描述
在MVC应用程序,我有是在经典视图/编辑使用这个大对象/创建模式。
当用户编辑对象我把它保存为:
公共BOOL SetMyObject(为MyObject NEWOBJECT){
为MyObject电流= GetObjectById(newObject.Id);
current.Prop1 = newObject.Prop1
...
current.PropN = newObject.PropN
db.SaveChanges();
}
为MyObject是pretty大,所以我想知道有没有更好的方式来做到这一点,不涉及每个属性分配。例如一些沿线 db.MyObject.UpdateObject(电流,TNEW)
。
泰。
您可以使用 ApplyPropertyChanges
方法。
从应用分离对象属性更改已附加到对象上下文的对象。
块引用>公共BOOL SetMyObject(为MyObject NEWOBJECT)
{
db.ApplyPropertyChanges(MyObjectSetNEWOBJECT);
db.SaveChanges();
}(其中,MyObjectSet是对象所属的实体集的名称)
In MVC app, I am having this big object that is used in classic view/edit/create pattern.
When user edits the object I save it as:
public bool SetMyObject(MyObject newObject) { MyObject current = GetObjectById(newObject.Id); current.Prop1 = newObject.Prop1 ... current.PropN = newObject.PropN db.SaveChanges(); }
MyObject is pretty big so I am wondering is there any better way to do this, not involving per-property assignments. For instance something along the lines
db.MyObject.UpdateObject(current, tnew)
.Ty.
解决方案You can use the
ApplyPropertyChanges
method.Applies property changes from a detached object to an object already attached to the object context.
public bool SetMyObject(MyObject newObject) { db.ApplyPropertyChanges("MyObjectSet", newObject); db.SaveChanges(); }
(where "MyObjectSet" is the name of the entity set to which the object belongs)
这篇关于更换实体框架对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!