"An entity object cannot be accessed by multiple instances of IEntityChangeTracker" in C# Entity Framework.

c# entity-framework


This error is thrown a lot, but I can't find the solution. I am new to the Entity Framework and in my first approach I got this error.

This is what I have. I have a company class and a branch class. Both classes have their own repository. A company has one Branch, while one branch can have multiple companies.

In my GUI I fill a combo with Branch objects, which I get from my BranchRepository:

    public IList<Branch> GetAllBranches()
        var query = _context.Branches;

        IList<Branch> branches = query.ToList();

        return branches;

This is result is the datasource of the branch combobox.

When I want to save the company, I do something like this:

company.VisitorAddress = txtVisitAddress.Text;
company.City = txtCity.Text;
company.CompanyName = txtCompany.Text;
company.PhoneNumber = txtPhoneNumber.Text;
company.ZipCode = txtZipcode.Text;
company.Branch = ((Branch)cmbBranches.SelectedItem);
company.Website = txtWebsite.Text;

Then, I call my company repository to save my company. Here is what the save method looks like:

public bool Save(Company company)
    _context.AddToCompanies(company);   // <-- This is where the error is thrown.

    return true;

When the save method is invoked, I get the error 'An entity object cannot be referenced by multiple instances of IEntityChangeTracker'.

Clearly I'm doing something wrong, but what?

9/26/2011 12:38:26 AM

Accepted Answer

Do you create new ObjectContext instance for each your repository? That could be source of problem because when you add Branche to Company it tries to add it to ObjectContext instance which cannot be done because it is still related to ObjectContext instance used to fill combobox. The way to go is to share ObjectContext instance among your repositories. Other possibility is to Detach Branch from first repository but it can have other consequencies.

2/26/2011 5:10:16 PM

Related Questions


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