抛出这个错误很多,但我找不到解决方案.我是实体框架的新手,在我的第一个方法中,我遇到了这个错误.
这就是我所拥有的.我有一个公司类和一个分支类.这两个类都有自己的存储库.公司有一个分公司,而一个分公司可以有多个公司.
在我的GUI中,我用Branch对象填充一个组合,我从BranchRepository获取:
public IList<Branch> GetAllBranches()
{
var query = _context.Branches;
IList<Branch> branches = query.ToList();
return branches;
}
Run Code Online (Sandbox Code Playgroud)
结果是分支组合框的数据源.
当我想要保存公司时,我会这样做:
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;
Run Code Online (Sandbox Code Playgroud)
然后,我打电话给我的公司存储库以保存我的公司.以下是save方法的样子:
public bool Save(Company company)
{
_context.AddToCompanies(company); // <-- This is where the error is thrown.
_context.SaveChanges();
return true;
}
Run Code Online (Sandbox Code Playgroud)
调用save方法时,我收到错误'IEntityChangeTracker的多个实例不能引用实体对象'.
显然我做错了什么,但是什么?
假设我在我的数据库中有多个数据库模式,例如:HumanRessources和Inventory.
在每个架构中包含多个表.您是否经常将数据库拆分为多个edmx,或者通常只将所有内容放在一个edmx中?
我正在考虑为每个模式创建一个edmx,但想知道这将如何影响unitorwork模式.通过阅读一些文章,ObjectContext将成为单元工作.通过定义2 edmx,我将得到2个ObjectContext:HumanRessourceContext和InventoryContext,这意味着每个将是一个单元工作.如果我希望对humanressource中的实体和inventorycontext中的实体进行的所有修改都是ATOMIC,那么这可以通过unitofwork模式实现吗?