实体框架InvalidOperationException保存
问题描述:
当我创建一个新的EF对象时,我首先将它附加到DbSet,然后将其导航属性之一设置为不同EF对象的新实例。然后我将第一个EF添加到DbSet并调用保存。我得到以下异常:实体框架InvalidOperationException保存
System.InvalidOperationException: The changes to the database were committed
successfully, but an error occurred while updating the object context. The
ObjectContext might be in an inconsistent state. Inner exception message: A
referential integrity constraint violation occurred: The property value(s) of
'Location.Id' on one end of a relationship do not match the property value(s)
of 'Pool.LocationId' on the other end.
这里是我的代码:
ORMContext context = new ORMContext();
var l = context.Locations.Create();
context.Locations.Attach(l);
...set properties
context.Locations.Add(l);
var p = context.Pools.Create();
context.Pools.Attach(p);
p.Location = l;
...set properties
context.Pools.Add(p);
context.SaveChanges();
我认为正在发生的是Location
对象是新的和Id
是0
默认。 EF正在更新Pool
(设置为0
)的外键,然后在将Location
对象保存到数据库后更新Location.Id
。因此Location.Id
现在设置为数据库中的关联值,如149
,并且Pool.LocationId
仍然设置为0
。
如何避免此异常?或者我想如何处理它?
答
您可以添加的位置,这样的参考实体将被设置
ORMContext context = new ORMContext();
var l = context.Locations.Create();
context.Locations.Attach(l);
...set properties
context.Locations.Add(l);
context.SaveChanges(); // save here, that way the location will get its Id
var p = context.Pools.Create();
context.Pools.Attach(p);
p.Location = l;
...set properties
context.Pools.Add(p);
context.SaveChanges();
这将是一个办法
同意后保存。这将解决问题。但是,这不是一个选项。然后它将保存任何其他更改,这些更改位于DbContext中,直到用户在UI中选择“保存”后才能强制执行。 –