This is my personal blog. The views expressed on these pages are mine alone and not those of my employer.

Tuesday, 11 September 2012

Entity Framework and the InvalidOperationException

While recently developing against the Entity Framework I stumbled across the following InvalidOperationException:

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"/>
to
<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.

Bear in mind however this manual modification needs done every time after adding tables or refreshing from the database.  For more information see the changes made to an .edmx file by the update model wizard.

4 comments:

  1. Have you eger considered about adding a little bit
    more than just your articles? I mean,what you ssay is
    valuable and all. Nevertheless just imagine if you added some geeat visuals or videos to give your posts more, "pop"!
    Your content is excellent but with images and clips, this blog could definitely be one of the
    best in its niche. Wonderful blog!

    my web site - pink dress sandals

    ReplyDelete
  2. This comment has been removed by a blog administrator.

    ReplyDelete
    Replies
    1. This comment has been removed by a blog administrator.

      Delete