我对EntityCollection进行了更改,EntityCollection是另一个EntityCollection的对象, 当我尝试保存这些更改时,我收到以下错误:
EntityCollection已初始化。该 应仅调用InitializeRelatedCollection方法进行初始化 在对象图的反序列化期间新的EntityCollection。
我可能缺少什么想法?
以下是我使用的代码。
public void UpdateCompanyManagement(Company newCompany)
{
Company oldCompany = entities.Companies.Where(c => c.COM_ID == newCompany.COM_ID).SingleOrDefault();
oldCompany.Managements = newCompany.Managements;
try
{
entities.SaveChanges();
}
catch (OptimisticConcurrencyException)
{
entities.Refresh(RefreshMode.ClientWins, newCompany.Managements);
entities.SaveChanges();
}
}
我可以使用以下代码成功保存父集合:
public void UpdateCompanyDetails(Company newCompany)
{
Company oldCompany = entities.Companies.Where(c => c.COM_ID == newCompany.COM_ID).SingleOrDefault();
entities.ObjectStateManager.ChangeObjectState(oldCompany.city, System.Data.EntityState.Modified);
oldCompany = newCompany;
try
{
entities.SaveChanges();
}
catch (OptimisticConcurrencyException)
{
entities.Refresh(RefreshMode.ClientWins, oldCompany);
entities.SaveChanges();
}
}
答案 0 :(得分:2)
答案 1 :(得分:0)
经过大量研究,我发现我的数据库/模型设置存在问题(因为我使用的是遗留数据库)。我的数据库中的大多数表都没有主键,而那些没有主键的表没有身份规范,这导致了问题。所以我更正了数据库并更新了我的模型。
而且,我最终找到了一种编写干净EF代码的简单方法。
两个函数中的代码可以重写如下:
public void UpdateCompanyManagement(Company company, int mgmtID)
{
var management = company.Managements.Where(m => m.M_ID == mgmtID).SingleOrDefault();
management.name = "new name";
management.position = "new position";
// edit all you want, then save
// no further code is required
// except you've done something wrong somewhere
try
{
entities.SaveChanges();
}
catch (OptimisticConcurrencyException)
{
entities.Refresh(RefreshMode.ClientWins, company);
entities.SaveChanges();
}
}
还有,
public void UpdateCompanyDetails(Company company)
{
company.name = "new company name";
company.address = "new company address";
// edit all you want then save
// no further code is required
// except you've done something wrong somewhere
try
{
entities.SaveChanges();
}
catch (OptimisticConcurrencyException)
{
entities.Refresh(RefreshMode.ClientWins, company);
entities.SaveChanges();
}
}
谢谢,彼得维京人! :)