3

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

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

You should initialize the Id of new entities you add/attach with a random Id (like Guid.NewGuid().GetHashCode() if you use Int32 as Id-type)

Otherwise have all entities the default Id of 0, and so will the ObjectStateManager throw an exception when you attach the entities.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.