2

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?

LU RD
  • 34,438
  • 5
  • 88
  • 296
Reynier Booysen
  • 281
  • 2
  • 14
  • 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. https://entityframework.codeplex.com/workitem/864 – Mickey Puri Mar 18 '14 at 09:23

3 Answers3

2

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).

Community
  • 1
  • 1
Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670
  • Thanks Ladislav, I looked into using POCO's (Code-First) for the EF. It seems likfe the way to go as it gives you more control and flexibility. Although there is a bug in 4.3 and I will have to wait for the service pack. I found a way around for this issue that I will post below. – Reynier Booysen Feb 23 '12 at 08:37
  • Hi @Ladislav Mrnka is your comment above still true with Code First? – Kirsten May 19 '13 at 01:14
0

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.

Community
  • 1
  • 1
codetuner
  • 316
  • 3
  • 8
0

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?

Reynier Booysen
  • 281
  • 2
  • 14