Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"... an error occured while updating the object context. The ObjectContext might be in an inconsistent state...."

In my application, I have a method that I call from code which seeds the database and this works fine.

I Have just created a new big method which also adds a lot more data to the database.

When I call this, it appears to work fine the first time it has run, but, if I run it again within a few minutes of the previous attempt, I get the following error:

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.

I am unsure how to fix this, can anyone advise anything? (other than not to run this within a few minutes of the last attempt!).

like image 219
Wil Avatar asked Nov 04 '22 05:11

Wil


1 Answers

This Error usually occurs when you try to save an entity model which has not defined well the primary key (composite key) as like in the database.

Define the keys in EntityTypeConfiguration file like

this.HasKey(f => new { f.ID1, f.ID2 });
like image 124
Nalan Madheswaran Avatar answered Nov 09 '22 03:11

Nalan Madheswaran