2
votes

I am trying to attach and add disconnected entities to an Entity Framework context. For example:

I have a Customer entity and a navigation property to detail Order entity. The idea is to get the Customer entity and make modifications to the entity and then also add new Order entities to the Customer entity.

The problem starts when I try to Attach (I assume this is the correct method to use.) the Customer entity. Because the whole object graph is now being attached I get the following error:

"An object with a temporary EntityKey value cannot be attached to an object context."

I understand that the error is because of the added Order entities that should be Added and not Attached.

Is there a way to Attach or Add a existing entity with new child entities to a context?

3
There has been a feature request for better reattachment of disconnected entity graphs for some time on Codeplex. Suggest visiting it and if you concur add your voice for this feature. entityframework.codeplex.com/workitem/864 - Mickey Puri

3 Answers

2
votes

If you want to use Attach this way you should not use EntityObject based entities - use POCOs instead. Anyway you will still have to traverse whole object graph and set correct state (modified, added, deleted) to every entity and independent association. At the end of the day attaching detached object graph is very hard even with POCOs - the best way is not attaching the graph but instead load the same data from database and sync detached graph with loaded graph (you must code it yourselves).

0
votes

After some research I found a work around for this issue:

Rather than attacthing the Customer object back to the context I now Add the Customer object to the context and then change the state of the object to Modified.

I have to copy the Customer object into a new Customer object to get rid of the EntityKey (you can not add a object with a EntityKey, you have to Attach it) and then add the new Customer object to the context using the AddObject method.

It is a bit ugly but it works. I am open for any other suggestions?

0
votes

The problem you describe was also the subject of my article on CodeProject: Reattaching Entity Graphs with the Entity Framework .

Note that the latest code is available on ef4tiers.codeplex.com.