记录一下遇到的错误和解决方法。
主要错误信息如下:
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: Saving or accepting changes failed because more than one entity of type 'XXX' have the same primary key value. Ensure that explicitly set primary key values are unique. Ensure that database-generated primary keys are configured correctly in the database and in the Entity Framework model. Use the Entity Designer for Database First/Model First configuration. Use the 'HasDatabaseGeneratedOption" fluent API or 'DatabaseGeneratedAttribute' for Code First configuration.
通过错误信息得知是数据保存成功,但更新实体对象时键值冲突导致的错误。
经过分析代码发现,执行了以下相关操作:
1.读取一批数据。
2.通过存储过程在数据库中清除了该批次数据。
3.重新添加了同键值的数据。
此时出现前文描述错误。因步骤2的存储过程的执行结果不影响步骤1中已经加载的数据,导致步骤3添加的数据出现键值冲突。
解决方法:
步骤1时不读取整个对象,而是筛选部分数据,经过筛选的数据并不会在实体对象中缓存,因此避免了出现该问题。