Last post Apr 05, 2016 07:00 AM by Yohann Lu
Apr 01, 2016 10:14 PM|cowasaki|LINK
I am getting a duplicate key value error while inserting list items into a bridge table.
The records are added, but will generate an duplicate key value error on the dbContext.SaveChanges(); method.
How can I prevent this error? many thanks for any help.
foreach (MyType li in listitems)
Apr 02, 2016 03:57 AM|navneetmitawa|LINK
plz check here
Apr 05, 2016 07:00 AM|Yohann Lu|LINK
From your description, I think it may cause by the following reasons.
When you add MyType to your model, Entity Framework will think that you have a new object. it will use the primary key you provide yourself. In your case this is the PK of the detached object. Thus, when EF tries to insert this entry it will throw the above
exception because an entity with that key is already in there.
The following information provides some solutions for your reference.
1: Violation of primary key Entity Framework Code First:
2: Solving the Detached Many-to-Many Problem with the Entity Framework: