14

I'm trying to learn how to use the Entity framework but I've hit an issue I can't solve. What I'm doing is that I'm walking through a list of Movies that I have and inserts each one into a simple database.

This is the code I'm using

private void AddMovies(DirectoryInfo dir)
{
    MovieEntities db = new MovieEntities();
    foreach (DirectoryInfo d in dir.GetDirectories())
    {
        Movie m = new Movie { Name = d.Name, Path = dir.FullName };
        db.AddToMovies(movie);
    }
    db.SaveChanges();
}

When I do this I get an exception at db.SaveChanges() that read.

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 haven't been able to find out what's causing this issue. My database table contains three columns
Id int autoincrement
Name nchar(255)
Path nchar(255)

Update: I Checked my edmx file and the SSDL section have the StoreGeneratedPattern="Identity" as suggested. I also followed the blog post and tried to add ClientAutoGenerated="true" and StoreGenerated="true" in the CSDL as suggested there. This resulted in compile errors ( Error 5: The 'ClientAutoGenerated' attribute is not allowed.). Since the blog post is from 2006 and it has a link to a follow up post I assume it's been changed.

However, I cannot read the followup post since it seems to require an msdn account.

Paxxi
  • 446
  • 1
  • 5
  • 11
  • 1
    The answer for me was to set the `StoreGeneratedPattern="Identity"` on the property, [see here for more details](http://www.matthewedmondson.info/2012/09/entity-framework-and.html). – m.edmondson Sep 12 '12 at 22:24
  • Also it occurs when you use SotredProcedure mappings for the INSERT, UPDATE, DELETE and your ID key is a computed key inside the SP. – Hamed Zakery Miab Sep 17 '14 at 04:00

8 Answers8

10

I found the solution to this.

What happened was that when I created my table I forgot to add the primary key and set (Is Identity) property to yes. I then created my Entity model and got this error.

I went back and fixed my database table but I still hade the weird Exception. What solved the problem in the end was to remove the entity and re-create it after the table was fixed.

No more exceptions :)

Paxxi
  • 446
  • 1
  • 5
  • 11
7

last time I tried the following code and I said it is working fine

bs.SuspendBinding();
Data.SaveChanges();
bs.ResumeBinding();

The important things which I wana tell you today are that:

1- if we use the above code to suspend binding we have to do more code to fix a lot of scenarios like index lost in the collections and the master detail bindings

2- if we use the following code instead of the above code we will see the exception gone and every thing will be ok where no need to write more code

        Data.SaveChanges(System.Data.Objects.SaveOptions.None);

I hope this solves your similar problems

thank you friends

6

This exception seems to tell you that you have equal values in severals rows in the Id column, which is supposed to only have unique values, because it's a key column. Entity Framework can handle such columns in two ways: either you (the Client) generates unique values, or the Server generates unique values. In your case it seems logical to allow the Server to generate autoincremented keys.

Do you have the StoreGeneratedPattern key set for the Id column in your SSDL file?

Here is an example from this blogpost:

<EntityType Name="rooms" Key="id">
    <Property Name="id" Type="int" Nullable="false" 
              StoreGeneratedPattern="Identity" />
    <Property Name="name" Type="nvarchar" Nullable="false" MaxLength="50" />
</EntityType>
Massimiliano
  • 16,770
  • 10
  • 69
  • 112
  • In EF4 is "Identity" instead of "identity" – Jader Dias Feb 23 '12 at 13:09
  • Thank you! This problem has been driving me nuts for the last week or so. I did have to manually edit the file though. Changing it in the properties only added an annotation mark. – Htbaa Mar 16 '12 at 16:02
2
System.Data.Objects.SaveOptions.None

This solves the problem but I'm wondering what's the difference between uning none or the other options.

Morad
  • 21
  • 1
1

if you have a bindingsource bound, you should call the suspendbinding:

        bs.SuspendBinding();
        Data.SaveChanges();
        bs.ResumeBinding();
0

Also Check if you set the "Is Identity" property for another column to "yes" and you are inserting a duplicated values into it.

major
  • 323
  • 1
  • 4
  • 11
0

I had the similar issue with table relationship spanning three levels Like Customer->Order->Order-Details with oracle 12C Auto-ID Trigger for key generation. Insertion using SaveChanges() was throwing System.InvalidOperationException.

Solution: Augmenting function SaveChanges(System.Data.Objects.SaveOptions.None) prevents system to use temporary EntityKeys in state of object graph and in result exception is avoided.

hyde
  • 60,639
  • 21
  • 115
  • 176
A_Basit
  • 21
  • 2
  • 2
    This is not answer of the question. If you have similar problem than you may post another question. See [How to write good answer](http://stackoverflow.com/help/how-to-answer) – Yagnesh Agola Jun 10 '14 at 05:07
0

Check if Primary Keys are missing in any of your etities, if yes, then create them, and do the "UpdateModel from Database"

this should Solve the problem

Mahika
  • 662
  • 2
  • 11
  • 21