5

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!).

Wil
  • 10,234
  • 12
  • 54
  • 81
  • 1
    possible duplicate of [InvalidOperationException when calling SaveChanges in .NET Entity framework](http://stackoverflow.com/questions/1008582/invalidoperationexception-when-calling-savechanges-in-net-entity-framework) – Eranga Feb 12 '12 at 23:54
  • @Eranga - I have read through that, but, I can't relate to that issue or fix this with that solution. – Wil Feb 13 '12 at 00:00
  • Very hard to answer without an insight into the relevant classes (PK and FK properties at least). – H H Feb 13 '12 at 00:13
  • @HenkHolterman That is what I was fearing :( The code is huge and I am not sure where the error is... I don't think people will want to read through all this! ... I'll get there! – Wil Feb 13 '12 at 00:41
  • @Wil could you figure out what was happening? – Campinho May 22 '12 at 16:02
  • @Campinho - Never got a good answer - in the end, I switched to using SQL Enterprise instead of express (I think it was, I can't honestly remember, it was a while ago) and the error went away... along with a few other errors. – Wil May 22 '12 at 16:42

2 Answers2

2

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 });
Nalan Madheswaran
  • 10,136
  • 1
  • 57
  • 42
0

Possible duplicate of:

Here are u useful links on working with self-tracking entities and the Object State Manager

Community
  • 1
  • 1
Abbas
  • 14,186
  • 6
  • 41
  • 72