我正在使用带有 MVC 和 POCO 的 EF5,需要一点帮助
我有一个更新功能,它传递了一个断开连接的 POCO。POCO 有一个“导航属性”集合,例如:Provider has
public virtual ICollection<Company> Companies { get; set; }
当 Provider 被加载(并且旧的上下文关闭)时,它有两个 Company 对象,现在它有四个,我想更新。
我认为下面的代码可能有效,但公司没有更新(但提供者的非导航属性(如字符串名称 {get;set} 仍然更新正常)并且没有错误
public void Update(Provider entity)
{
// Existing entity
_context.Entry(entity).State = EntityState.Modified;
if (entity.Companies.Any())
{
//try to tell EF about the companies
foreach (var company in entity.Companies)
{
//the company exists already - let the context know....
_context.Entry(company).State = EntityState.Modified;
_context.Companies.Attach(company);
}
}
}
... 然后:_unitOfWork.SaveChanges();
对于插入的 Provider with Companies 我已成功使用:
if (entity.Companies.Any())
{
//these are not to be created - they exist -
//I want EF to add them as nav properties
foreach (var company in entity.Companies)
{
//the company exists already - let the context know....
_pvpContext.Companies.Attach(company);
}
}
// New entity
_pvpContext.Entry(entity).State = EntityState.Added;
我要去阅读 Julia Lerman 的书,因为 EF 正在杀死我 - 但我非常感谢在此期间更新“公司”的任何帮助 - Thx
编辑:我尝试了@Manos 的善意建议:
List<Company> companies = new List<Company>();
if (entity.Companies != null && entity.Companies.Any())
{
//pull out the Companies from the POCO
companies = entity.Companies.ToList();
//remove them
entity.Companies = new Collection<Company>();
entity.Companies.Clear();
}
// pass existing entity to the context, tagged as modified
_pvpContext.Entry(entity).State = EntityState.Modified;
if (companies.Any())
{
//now re-add the companies while the context is listening. ffs.
foreach (var company in companies)
{
entity.Companies.Add(company);
}
}
如果我将 Provider.Companies 添加到上下文中(如插入),我会得到:
违反主键约束“PK__tmp_ms_x__679519B7F943FD8D”。无法在对象“dbo.ProviderCompany”中插入重复键。重复键值为 (5, 3)
- 这很奇怪,因为 (provider 5, company 3) 没有复合键 - 所以它可能试图在这里添加两次?
如果我不预先添加 Provider.Companies 我得到:
在 System.Data.Entity.Internal.InternalContext.SaveChanges() 在 System.Data.Entity.Internal.LazyInternalContext.SaveChanges() 在 System.Data.Entity.DbContext.SaveChanges()