开发者

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

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开发者_JS百科 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.
    _context.SaveChanges();

    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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜