[英]Entity Framework Modify Detached Object
由于对此http://msdn.microsoft.com/zh-cn/library/vstudio/bb896248(v=vs.100).aspx的修改,我有些困惑。
这似乎表明如果我以分离状态修改对象,则在重新附加时,应使用ApplyOriginalValues而不是ApplyCurrentValues。 但是,执行此操作时,似乎永远不会像示例中那样更新对象,除非在重新附加对象后修改该对象。 但是,如果我在附加后进行修改,那么使用哪一个(应用原件或应用电流)似乎并不重要。
这是我的代码:
//this never works
private void UpdateWithOriginal(Category cat, string name)
{
using (TestContext ctx = new TestContext())
{
cat.Name = name;
ctx.Categories.Attach(cat);
ctx.ApplyOriginalValues("Categories", cat);
var state = ctx.ObjectStateManager.GetObjectStateEntry(cat).State; //never modified state here
ctx.SaveChanges();
}
}
//this always works
private void UpdateWithCurrent(Category cat, string name)
{
using (TestContext ctx = new TestContext())
{
ctx.Categories.Attach(cat);
cat.Name = name;
ctx.ApplyCurrentValues("Categories", cat);
var state = ctx.ObjectStateManager.GetObjectStateEntry(cat).State;
ctx.SaveChanges();
}
}
有谁知道为什么MSDN链接似乎表明//这永远不起作用,位应该起作用?
最终变得如此简单。 我不知道为什么我不明白。 这是解决方案:
private void UpdateWithOriginal(Category cat, string name)
{
Category updatedObject = new Category()
{
CategoryID = cat.CategoryID,
Name = cat.Name,
Topics = cat.Topics
};
updatedObject.Name = name;
using (TestContext ctx = new TestContext())
{
ctx.Categories.Attach(updatedObject);
ctx.ApplyOriginalValues("Categories", cat);
var state = ctx.ObjectStateManager.GetObjectStateEntry(updatedObject).State; //never modified state here
ctx.SaveChanges();
}
}
我所缺少的是这个。 您有两个对象,原始对象和更新对象。 分离后,将其发送给WCF服务,进行更改,将对象发回,最后将对象重新创建为更新的对象。 现在,为了更新上下文,您需要两个对象,因为使用给定的代码,如果将updatedObject附加到上下文中,则实体的状态为:
没有什么不同,所以.SAveChanges()不会做任何事情。 由于您已附加了更新的对象,因此必须使用ApplyOriginalVAlues(“ Categories”,OriginalCategory)导致此情况:
现在,您有了一个已修改的对象,当您调用.SaveChanges()时,更改将生效。 如果您附加了原始对象,则相反的情况是正确的(您无需修改原始值,而是当前值,因此可以使用ApplyCurrentVAlues())。
我认为您只是误读了MSDN文章。
从MSDN ApplyOriginalValues定义:
Copies the scalar values from the supplied object into set of original values for the object in the ObjectContext that has the same key.
从MSDN的ApplyCurrentValues定义:
Copies the scalar values from the supplied object into the object in the ObjectContext that has the same key.
这正是您所看到的行为。 ApplyOriginalValues
返回数据库并更新值。 ApplyCurrentValues
使用您拥有的对象中的值,因此您可以更新更改。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.