EF, Automapper exception, "Attaching an entity of type ... failed because another entity of the same type already has the same primary key value"

automapper c# entity-framework

Accepted Answer

ZZZ_tmp
2
8/5/2015 1:44:13 PM

Popular Answer

Observing the error code: Because another entity of the same type already has the same primary key value, attaching failed.

This issue also arose for us in the past:

  1. We utilized a dbcontext to load an object A that has a child object B, and then we used these objects on the GUI.
  2. We loaded another object B' (with the same PK as B) with a different database context when approving a post from the GUI. This object was only needed to confirm certain parameter modifications.
  3. Then we attempted to attach object A with child object B to the dbcontext in order to save it to the database, but an error was encountered.

The issue happened as a result of object B' already existing with the same PK in a different database context.

By avoiding duplicate keys of the same object type within a single dbcontext, we were able to address this issue.

  1. Retrieving object A and object B, setting all of its attributes using GUImodels, and finally flushing it in the direction of the database.
  2. We stopped attaching the GUImodels (Object A and B from previous dbcontext)
  3. We stopped obtaining item B individually.

Within your code: Is it possible that object property has already been loaded as a child object of object src and has automatically mapped to object property, adding it to the context and notifying an objecttype with the same pk?

I discovered a similar post here.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow