当我创建一个新的EF对象时,我首先将它附加到DbSet,然后将它的一个导航属性设置为另一个EF对象的新实例。然后我将第一个EF添加到DbSet中,并调用save。我得到了以下异常:
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
。
如何避免此异常?或者我该怎么处理呢?
发布于 2016-09-07 01:46:20
您可以在添加位置后保存,这样就可以设置对实体的引用
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();
那将是一种方法
https://stackoverflow.com/questions/39354837
复制相似问题