Tuesday, 18 November 2014
Entity Framework exception - adding new Detached Object to the DbContext
Entity Framework exception - adding new Detached Object to the DbContext? How to?
When you see this exception:
Exception: Attaching an entity of type 'Image' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate.
This just mean that you need to properly handle detanched entities Ids. This exception means that two of your newly added entities have the same Id. Typically the value of the Id is 0.
So the solution is that you need to manually change Ids. You need to make sure that every Id from new added entity is different. Typically you should put negative Ids. Like -1, -2, -3, ...