C#Entity Framework“IEntityChangeTracker的多个实例不能引用实体对象”

这个错误引起了很多,但我找不到解决方案。 我是entity framework的新手,在我的第一个方法中,我遇到了这个错误。

这就是我所拥有的。 我有一个公司类和一个分支类。 这两个类都有自己的存储库。 公司有一个分公司,而一个分公司可以有多个公司。

在我的GUI中,我用Branch对象填充一个组合,我从BranchRepository获取:

public IList GetAllBranches() { var query = _context.Branches; IList branches = query.ToList(); return branches; } 

结果是分支combobox的数据源。

当我想要保存公司时,我会这样做:

 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; 

然后,我打电话给我的公司存储库以保存我的公司。 以下是save方法的样子:

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

调用save方法时,我收到错误’IEntityChangeTracker的多个实例无法引用实体对象’。

显然我做错了什么,但是什么?

您是否为每个存储库创建新的ObjectContext实例? 这可能是问题的根源,因为当您将Branche添加到Company时,它会尝试将其添加到ObjectContext实例,这是无法完成的,因为它仍然与用于填充combobox的ObjectContext实例相关。 ObjectContext是在您的存储库之间共享ObjectContext实例。 其他可能性是从第一个存储库中Detach分支,但它可能有其他后果。