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 was trying to insert a new record into a table that contained an auto-generated value. Due to the way the entity model wizard generates it's factory methods meant I had to provide a 'dummy' value for the auto-generated key.
For example in the following code the first parameter is required, even though the database will auto-generate this:
Employee newEmployee = Employee.CreateEmployee(0, "Jansen", "Jan"); context.AddObject("Employees", newEmployee); context.SaveChanges();
It turns out however that you also need to manually update the model (.edmx) so that it doesn't use the 'dummy' value as the object's key within the ObjectStateManager.
To do this you'll need to open it as text (in solution explorer right click the model, select "Open With" and select "Text Editor"). Then navigate to the auto-generated property in the storage part of your model (within the
<edmx:storagemodels>tag) and add
StoreGeneratedPattern="Identity"as an attribute.
For example change
<Property Name="ID" Type="number" Nullable="false" Precision="11"/>
<Property Name="ID" Type="number" Nullable="false" Precision="11" StoreGeneratedPattern="Identity"/>
The StoreGeneratedPattern is an enumeration which indicates whether the column in the database needs a value on insert and update operations, and since it's auto-generated on the database it doesn't. Therefore by specifying this on the attribute you prevent the exception being thrown.