通过关系更新实体时出现IEntityChangeTracker错误 [英] IEntityChangeTracker error when updating entity through their relation

查看:67
本文介绍了通过关系更新实体时出现IEntityChangeTracker错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试从其引用更新实体,如下所述

我收到此错误

System.Data中出现类型'System.InvalidOperationException'的异常。 Entity.dll但未在用户代码中处理

附加信息:IEntityChangeTracker的多个实例无法引用实体对象。

如果我不想要如何实现这一点单独处理每个实体

用户[id名称]

操作[id text userid resultId]]

结果[id resulttxt]

i been trying to update entity from its reference as explained below
iam getting this error
An exception of type 'System.InvalidOperationException' occurred in System.Data.Entity.dll but was not handled in user code
Additional information: An entity object cannot be referenced by multiple instances of IEntityChangeTracker.
how to make this happen if i dont want to deal with each entity alone
user[id name]
action[id text userid resultId]]
result[id resulttxt]

public static void test1(action act) {
             act.text="132";
             act.user.name="test";
             act.result.resulttxt="test";
             testEntities e = new testEntities();
             e.actions.Attach(act);
             e.SaveChanges();
       }
          testEntities b = new testEntities();
          action act = b.actions.Include("user").Include("result").Where(x => x.id == 9).FirstOrDefault();
          test1(act);

推荐答案

为什么要在Test1方法中创建第二个DbContext?你不应该因为现在你试图使用两个不同的上下文来跟踪同一个实体而这是行不通的。 Test1,因为它没有创建上下文并且没有向要跟踪的上下文添加任何内容,所以不应该关心保存任何更改。这应该留给创建上下文实例的调用者。
Why are you creating a second DbContext inside your Test1 method? You shouldn't be because now you're trying to track the same entity using two different contexts and that doesn't work. Test1, since it didn't create a context and didn't add anything to the context to track, shouldn't be concerned at all with saving any changes. That should be left up to the caller that made the context instance.


你的意思是这样的



you mean like this

 public static void test1(action act) {       
              act.text="132";
              act.user.name="test";
              act.result.resulttxt="test";
                }
           testEntities b = new testEntities();
           action act = b.actions.Include("user").Include("result").Where(x => x.id == 9).FirstOrDefault();
 test1(act);
b.SaveChanges();





以及它是否有效,但为什么我无法附加该实体并保存其他更改context



well yes it worked but why i cant attach that entity and save change in the other context


有一个关于如何解决此异常的博客http://www.admarketspace.com/Blog/Index。源代码也可以下载
There is a blog on how to solve this exception http://www.admarketspace.com/Blog/Index. The source code is also available for download


这篇关于通过关系更新实体时出现IEntityChangeTracker错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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