问题描述
我收到了错误
一个实体对象不能被多个实例引用IEntityChangeTracker
An entity object cannot be referenced by multiple instances of IEntityChangeTracker
尝试创建新实体并将其保存到数据库时.
when trying to create a new entity and save it to the DB.
我了解错误以及它通常是如何发生的,但在这种情况下,我所做的只是创建一个新实体并在保存之前向其添加一些 int
,而不是添加任何其他实体其他情况.
I understand the error and how it normally occurs, but in this instance all I am doing is creating a new entity and adding a few int
s to it before saving, not adding any other entities from other contexts.
我已经包含了导致错误的函数.正如您所看到的,它被传递了一个 EndProduct
,它是一个实体,它由与 _billableRepository
中的上下文不同的上下文跟踪,但因为我不想无论如何,将该实体分配给新创建的计费,我看不出它是如何成为问题的.
I have included the function that is causing the error. As you can see it is being passed an EndProduct
which is an entity which is being tracked by a different context to the one in the _billableRepository
, but since I am not trying to in anyway assign that entity to the newly created billable I don't see how it can be a problem.
我能看到错误发生的唯一方法是因为分配给新 Billable
的几个 int
值取自现有 EndProduct
被不同的上下文跟踪,但 IEntityChangeTracker
肯定不会跟踪实体的各个原语吗?
The only way I can see the error happening is because a couple of the int
values that are being assigned to the new Billable
are taken from the existing EndProduct
that is being tracked by a different context, but surely the IEntityChangeTracker
doesn't track the individual primitives of an entity?
public void AddBillable(EndProduct endProduct, int? purchaseId, string centreCode, int userId)
{
if (endProduct.Product != null)
{
var existingBillableForUserForProductId = _billableRepository.GetQuery(b => b.UserId == userId && b.ProductId == endProduct.ProductId);
if (endProduct.BillablePartId != null && !existingBillableForUserForProductId.Any())
{
var billable = new Billable {
ProductId = endProduct.ProductId.Value, //int
UserId = userId, //int
PartId = endProduct.BillablePartId.Value, //int
DateAdded = DateTime.UtcNow, //datetime
PurchaseId = purchaseId, //int
CentreCode = centreCode //string
};
_billableRepository.Add(billable); //error here
_billableRepository.UnitOfWork.SaveChanges();
}
}
}
推荐答案
最可能的原因是与您使用的任何依赖注入工具有关.
The most likely cause of this is to do with any dependency injection tool you're using.
每个工作单元应该只有一个 DbContext
在起作用.如果您每次都更换新的,请确保将旧的丢弃.
There should only be one DbContext
in play per unit of work. If you are newing up a new one each time, make sure the old one is disposed of.
否则,您将有多个相同上下文的实例并排运行.
Otherwise, you will have multiple instances of the same context running alongside each other.
这是更改跟踪器感到困惑并且无法跟踪对您的实体所做的更改的地方.
This is where the change tracker gets confused and is unable to track changes to your entities.
这篇关于实体框架“一个实体对象不能被多个 IEntityChangeTracker 实例引用"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!