I am getting the error
An entity object cannot be referenced by multiple instances of IEntityChangeTracker
when trying to create a new entity and save it to the DB.
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.
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.
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();
}
}
}