我首先在EF 5数据库中使用Attach添加/更新数据库中的行。
适用于数据库中尚不存在的实体。
在尝试附加现有实体时,它会抛出异常An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.
。
我已尝试过扩展,就像其他答案一样,没有人工作。
注意是我在没有设置PK的情况下附加了一个实体,我没有实现代码中的这些信息。
代码
var db = new XXX_DevEntities();
int YearMax = DateTime.Today.AddYears(5).Year;
var existent = (from a in db.BusinessDays
where a.Year < YearMax
select new { a.Year, a.Month }).ToList();
foreach (var aj in ajustes)
{
for (int i = 1; i < 13; i++)
{
var entidade = new BusinessDays { Year = aj.Year, Month = i };
db.BusinessDays.Attach(entidade); // THROWS EXCEPTION HERE
entidade.Qtd = aj.ValorMonth(i);
db.Entry(entidade).State = existent.Contains(new { Year = aj.Year, Month = i }) ? EntityState.Modified : EntityState.Added;
}
}
db.SaveChanges();
答案 0 :(得分:0)
我发现了......
我选择了另一种方法,我通过从数据库中检索它(实际上是从数据库集的本地缓存中)来附加PK实体。
var db = new XXX_DevEntities();
int YearMax = DateTime.Today.AddYears(5).Year;
var existent = (from a in db.BusinessDays
where a.Year < YearMax
select a).ToList();
foreach (var aj in ajustes)
{
for (int i = 1; i < 13; i++)
{
var codBusinessDay = diasUteisExistentes.Where(x => x.Year == aj.Year && x.Month == i).Select(x => x.CodBusinessDay).FirstOrDefault();
var entidade = new BusinessDays { CodBusinessDay = codBusinessDay };
db.BusinessDays.Attach(entidade);
entidade.Year = aj.Year;
entidade.Month = i;
entidade.Qtd = aj.ValorMonth(i);
db.Entry(entidade).State = codBusinessDay > 0 ? EntityState.Modified : EntityState.Added;
}
}
db.SaveChanges();