0

I'm working on an application that uses Entity Framework 4.0 (and as far as i know we cannot change it).

I need to make deep copies of object, in the case the users selects and object it will get a full copy assigned to him, with all the navigation properties and all created.

I know that in entity framework 4.1 and later version i could use de AsNoTracking and then just add it, but i don't know how to do it in entity framework 4.0. Is there any easy way?

Edit: Thanks to what @PanagiotisKanavos said i realized that what i really wanted was to detach the entity. It kind of solved my problem but not completly, doing:

ctx.Set.Detach(entity) 

Detached the entity but i lost all the associations, so any idea how to detach the rest of the association graph?

Update: After a lot of experiments i've run out of ideas, i've tried to deep clone, and detatch but when i Add i gives me and exception.

If i only detach i lose all associations so any idea ?

  • This could be helpful http://stackoverflow.com/questions/5249633/deep-clone-using-entity-framework – dmigo Jun 17 '15 at 08:25
  • Deep cloning has nothing to do with Entity Framework or databases, it's only about objects. It also won't create any *new* records, as the entity IDs will remain the same. It will only result in updating the existing records – Panagiotis Kanavos Jun 17 '15 at 08:37
  • Is the actual question how to detach objects in EF 4? You don't need `AsNoTracking` to do this, you can use `ObjectContext.Detach` on all related objects – Panagiotis Kanavos Jun 17 '15 at 08:43
  • @PanagiotisKanavos Yes, you are right it's not deep cloning what i want (I used becuase i did't know the right term), well I want to create a copy of the data, to later store it in the database. But i need to have a copy of the associations (and all the data). The thing is i know with AsNotracking i cound modified de objected and then add it as a new object (or that is my undersdanding) – Curious Bystander Jun 17 '15 at 10:01
  • `AsNoTracking` creates detached objects and can load an entire detached graph (which is what you want). You can detach objects with `Detach` *but* you have to do it individually for each related object. – Panagiotis Kanavos Jun 17 '15 at 10:06
  • @PanagiotisKanavos If i undestood you correctly, you mean that i'll have to detatch every association manually? – Curious Bystander Jun 17 '15 at 10:13

1 Answers1

0

You need to make your class [Serializable] and include

using System.Runtime.Serialization.Formatters.Binary;
using System.IO;

Then

public static T DeepCopy<T>(T objectToCopy)
{
 using (var memStr = new MemoryStream())
 {
   var binFormatter = new BinaryFormatter();
   binFormatter.Serialize(memStr, objectToCopy);
   memStr.Position = 0;
   return (T) formatter.Deserialize(memStr);
 }
}