实体框架保存时的InvalidOperationException

本文关键字:InvalidOperationException 保存 框架 实体 | 更新日期: 2023-09-27 18:05:49

当我创建一个新的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

如何避免此异常?或者我该怎么处理?

实体框架保存时的InvalidOperationException

您可以在添加位置后保存,这样对实体的引用将被设置

    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();

这是一种方法

相关文章:
  • 没有找到相关文章