IEntityChangeTracker的多个实例不能引用一个实体对象.在多个条目上 [英] An entity object cannot be referenced by multiple instances of IEntityChangeTracker. On multiple entries

查看:48
本文介绍了IEntityChangeTracker的多个实例不能引用一个实体对象.在多个条目上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个工作对象:

public class Work{
public int WorkId { get; set; }
public virtual Work RelatedWork { get; set; }
public virtual ICollection<Work> RelatedMultipleWorks { get; set; }
}

我正在生成一个这样的Work对象:

I'm generating an Work object like this :

Work myWork = new Work();

work mywork2 = new Work();
work mywork3 = new Work();

myWork.RelatedMultipleWorks.add(mywork2);
myWork.RelatedMultipleWorks.add(mywork3);

DbSaveChanges 上,出现此异常:

实体对象不能被的多个实例引用IEntityChangeTracker.

An entity object cannot be referenced by multiple instances of IEntityChangeTracker.

代码有什么问题?我怎样才能解决这个问题?谢谢.

What is wrong with the code? How can I fix this? Thanks.

我在这一行得到了异常:

I get the exception at this line :

_db.Works.Add(mywork);

这是我的DbSaveChanges行:

Here is my DbSaveChanges Line :

  _db.Works.Add(_myWork);
  _db.SaveChanges();
  result.Success= true;
  _provider.AddOrUpdate(mywork);

注意:在实际的代码中,工作实体具有更多的实体.就像数百个一样,所以我无法发布实际代码.

Note : In the actual code, Work entity has a lot more entities. Like hundreds, so I can't post actual code.

当我尝试使用 _db.Works.Add(_myWork2); 添加myWork2或myWork3时,仍然出现相同的错误.是由于缺少实体或类似原因导致此错误?

EDIT : When I try to add myWork2 or myWork3 using _db.Works.Add(_myWork2);, I still get the same error. Is this error because of a missing entity or something like that?

推荐答案

最终,这是这里提到的相同问题:

Ultimately, this is the same problem mentioned here: How can I use EF to add multiple child entities to an object when the child has an identity key?

如果您具有自动生成的 PK ,并在相同的上下文中执行了先前的udpate/delete后尝试执行 Add ,则会崩溃,因为最终多个对象同时具有相同的 PK .

If you have a auto generated PK and attempt to do an Add after doing a previous udpate/delete on the same context, it will crash because you end up with the same PKs for multiple objects at the same time.

要解决此问题,您必须将所有这些 WorkIds (我假设这是 PK )设置为 -1,-2,-3 及其对这些新数字的正确 FK 引用

您必须先添加所有新实体,然后再执行任何更新/删除操作,因为EF会意识到以后会设置这些ID.

To fix this, you must either set all those WorkIds (I assume this is the PK) to -1, -2, -3 and their proper FK references to those new numbers
OR
You must add all new entities first before you do any updates/deletes since EF will realize that those IDs will be set in the future.

这篇关于IEntityChangeTracker的多个实例不能引用一个实体对象.在多个条目上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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