实体框架修改分离的对象

时间:2013-03-02 17:31:15

标签: c# entity-framework

我有一些混淆,源于此http://msdn.microsoft.com/en-us/library/vstudio/bb896248(v=vs.100).aspx关于修改分离对象的问题。

这似乎表明我是否修改了处于分离状态的对象,当我重新连接时,我应该使用ApplyOriginalValues而不是ApplyCurrentValues。但是,当我这样做时,似乎永远不会像在示例中那样更新对象,除非我在重新附加它之后修改对象。 但是,如果我在附加后修改,那么我使用哪些(applyoriginal或applycurrent)似乎并不重要。

这是我的代码:

//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链接似乎表明//这个从不起作用,bit应该有用吗?

2 个答案:

答案 0 :(得分:1)

这最终变得如此简单。我不知道为什么我不理解它。以下是解决方案:

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,则实体的状态为:

  • 原始值 - 名称= Bob
  • 当前VAlues-姓名= Bob

没有什么不同,所以.SAveChanges()不会做任何事情。由于你附加了更新的对象,你必须使用ApplyOriginalVAlues(“Categories”,OriginalCategory)来导致这个:

  • Original VAlue:姓名= Steve
  • 当前值:Name = Bob

现在您有一个修改过的对象,当您调用.SaveChanges()时,更改将生效。如果附加原始对象,则反之亦然(您不需要修改原始值,而是修改当前值,因此使用ApplyCurrentVAlues())。

答案 1 :(得分:0)

我认为你只是误读了MSDN文章..

来自ApplyOriginalValues的MSDN定义:

Copies the scalar values from the supplied object into set of original values for the object in the ObjectContext that has the same key.

来自ApplyCurrentValues的MSDN定义:

Copies the scalar values from the supplied object into the object in the ObjectContext that has the same key.

这正是您所看到的行为。 ApplyOriginalValues返回数据库并更新值。 ApplyCurrentValues使用您拥有的对象中的值,因此您可以更新更改。

相关问题