抛出这个错误很多,但我找不到解决方案.我是实体框架的新手,在我的第一个方法中,我遇到了这个错误.
这就是我所拥有的.我有一个公司类和一个分支类.这两个类都有自己的存储库.公司有一个分公司,而一个分公司可以有多个公司.
在我的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的多个实例不能引用实体对象'.
显然我做错了什么,但是什么?
我有一个依赖EF的Windows服务,它运行正常,直到服务器出现故障.问题是在服务器再次启动后,它没有自行修复并仍然抛出错误:
内部错误:执行命令需要打开且可用的连接.连接的当前状态被破坏.
不是非常精通EF我不知道如何从这种情况中恢复,以及为什么它首先发生?有人曾经发生过这种事吗?