使用 Oracle ODP.NET 在 .NET Entity framework 中调用 SaveChanges 时出现 InvalidOperationException

InvalidOperationException when calling SaveChanges in .NET Entity framework with Oracle ODP.NET

我有一个代码可以从数据库中删除一些实体,然后重新插入更新的行。方案如下:

 db.BeginTransaction();
 try
 {
    //Delete some rows
    db.SaveChanges();
    //Add updated rows
    db.SaveChanges();
    db.Commit()
 }
 catch
 {
    db.Rollback();
    throw;
 }

在某些情况下,但一般情况下,我在第二次 SaveChanges 之后出现以下错误:

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: AcceptChanges cannot continue because the object's key values conflict with another object in the ObjectStateManager. Make sure that the key values are unique before calling AcceptChanges.

数据库是 Oracle,我使用 ODP.NET Oracle 提供程序使其与 Entity Framework 一起工作。已更新 table 使用复合主键。

长话短说 - 它是数据中重复的复合主键值。

一般来说,错误表明对象上下文或上下文与数据库之间出现某种不一致。这通常是由于同时修改了一些数据(通过 EF 以外的其他方式)引起的,例如通过存储过程,因此上下文变得过时。

但是在这种情况下,问题出在其他地方。即在复合键中。在数据中很容易忽略它,但如果我们有由三个、四个、五个值组成的主键,并且在要更新的行列表中的某处,键是重复的 Entity Framework 将抛出该异常。