Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert List of Objects using Entity Framework

Hi i am trying to attach multiple objects in ObjectContextManager and try to set their state in "Added" Mode. These objects have some navigational properties with them and when i try to attach any object after attaching the first object. It throws me the error

An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.

The reason seems to be very obvious but what will be its solution.

Kindly guide

like image 699
Manvinder Avatar asked Jul 13 '26 13:07

Manvinder


1 Answers

By calling Attach or AddObject on the entity you are actually attaching or adding whole object graph (EF traverse navigation properties and executes the operation on every related property). When you try to add or attach entity which was already attached or added as part of object graph you will get this exception. The solution is to understand your data model and call AddObject or Attach only for disjointed object graphs.

like image 146
Ladislav Mrnka Avatar answered Jul 16 '26 06:07

Ladislav Mrnka



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!