Entity Framework "An entity object cannot be referenced by multiple instances of IEntityChangeTracker"

c# entity-framework entity-framework-6

Question

I'm experiencing the issue

An entity object cannot be referenced by multiple instances of IEntityChangeTracker

while attempting to create and save a new entity to the database.

I am aware of the problem and how it often happens, but in this case, all I am doing is adding a few new entities.int without adding any more entities from other contexts before saving.

The function that is generating the problem is included. As can be seen, it is passing anEndProduct which is a subject of tracking in a different context from that of the one in the_billableRepository I don't understand how that can be an issue, however, as I am not attempting to in any way attach that object to the newly formed billable.

I can only imagine the issue occurring because a few of theint the new values that are being allocatedBillable are drawn from the currentEndProduct that a distinct context is tracking, but undoubtedly theIEntityChangeTracker doesn't keep track of an entity's individual primitives?

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();
        }
    }
}
1
7
6/23/2016 11:34:16 AM

Accepted Answer

ZZZ_tmp
11
6/23/2016 1:30:35 PM

Popular Answer

as per your model(GetById method) Try putting it like this:

var billable = _db.Billable. AsNoTracking().SingleOrDefault(i => i.BillableId == id);

Use AsNoTracking() to ensure that it produces a fresh query without caching the entities.System.Data.Entity.DbContext



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow