How to Deep Clone/Copy and entity in entity Framework 4.0?

732 views Asked by At

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 ?

1

There are 1 answers

1
Stoyan Uzunov On

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);
 }
}