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

  • Question

  • I am trying to add order and orderLine data into data base using EnityFramework. For the first time when  addToOrderDetails(...) is called I intentionally pass two rows in orderLine variable with  same primary key so it will throw exception when I try to call
    " x = laundaryEntities.SaveChanges();" after removing row having same primary key in orderLine I call addToOrderDetails() again but this time Exception is thrown at "laundaryEntities.Orders.AddObject(order);" 
    Message = "An entity object cannot be referenced by multiple instances of IEntityChangeTracker.".......
    Why is it still referenced? I am initializing a new Db() object every time I call addToOrderDetails(...)...
     public class Db
            LaundaryEntities laundaryEntities = new LaundaryEntities();
            public int addToOrderDetails(System.ComponentModel.BindingList<Order_Details> orderLine, Customer customer, Employee employee, Order order)
                int x = 0;
                foreach (Order_Details item in orderLine)
                order.Customer_Id = customer.Customer_Id;
                order.Employee_Id = employee.Employee_Id;
                order.Order_Date = DateTime.Now;
                    laundaryEntities.Orders.AddObject(order); // Second time Exception is thrown at this point
                    x = laundaryEntities.SaveChanges(); //I make it throw it exception here for the first time
                    return x;
                catch (Exception ex)
    public partial class Main : Form
    BindingList<Order_Details> orderLine;
    Order order;
    private Customer customer;
     private void toolStripButtonProcess_Click(object sender, EventArgs e)
                Db db = new Db();
               db.addToOrderDetails(orderLine, customer, employee, order) > 0; //here i am calling my method which will store data into databas
    Monday, December 26, 2011 12:57 PM


  • Hi Rizwan

    Welcome to MSDN Forum.

    Based on the issue, I think the order has already attached to another context and didn't detached. Though you create a new context every time, but when the last context disposed, the entity doesn't detached from it. There's a discussion about this problem in another case, I think it could help you. Please refer here. If it couldn't help you to solve the issue, please post your database schema here, this is, so I can reproduce the scenario.

    Best Regards

    Allen Li [MSFT]
    MSDN Community Support | Feedback to us

    Wednesday, December 28, 2011 2:53 AM