简体   繁体   中英

Error in MVC 5 with EF 6 “ System.InvalidOperationException: An entity object cannot be referenced by multiple instances of IEntityChangeTracker.”

This is the code I have for adding products to the database:

public void AddToCart(Product item)
{
    // Get the matching cart and album instances
    var cartItem = entities.Orders.FirstOrDefault(
        c => c.OrderGUID == ShoppingCartId
        && c.OrderItems.Where(p=>p.ProductId == item.ProductId).FirstOrDefault().ProductId == item.ProductId);

    if (cartItem == null)
    {
        // Create a new cart item if no cart item exists
        cartItem = new Order
        {
            InvoiceNumber = Guid.NewGuid().ToString(),
            OrderDate=DateTime.Now,
            OrderGUID = ShoppingCartId
        };
        entities.Orders.Add(cartItem);
    }
    else
    {
        // If the item does exist in the cart, 
        // then add one to the quantity
        cartItem.OrderItems.Where(p => p.ProductId == item.ProductId).SingleOrDefault().ProductQuantity++;
    }
    // Save changes
    entities.SaveChanges();

    OrderItem oi = new OrderItem()
    {
        OrderGUID = ShoppingCartId,
        ProductId = item.ProductId,
        ProductQuantity = item.Quantity,
        ProductPrice = item.ProductPrice,
        Product = item
    };

    entities.OrderItems.Add(oi);
    entities.SaveChanges();
}

When it hits this line

entities.OrderItems.Add(oi);

If when I get the above error. Any ideas?

At first glance I would suspect that the entities variable in this code, and the one the parameter "Product item" came from are not the same entity framework. When referencing an item, it must be loaded by the same entity framework data model.

You could try to reference by ID instead:

OrderItem oi = new OrderItem()
{
    OrderGUID = ShoppingCartId,
    ProductId = item.ProductId,
    ProductQuantity = item.Quantity,
    ProductPrice = item.ProductPrice,
    ProductID = item.ID // Changed here
};

entities.OrderItems.Add(oi);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM