Posts Tagged ‘Entity Framework’

With the adoptation of ORM, it is becoming increasingly useful to be able to clone an object graph. This is particualry useful when using the Entity Framework on the POCO model.

This extension method attaches itself to the object class. We use binary serialization to serialize into a memory stream then back out to the target class, essentially making a perfect copy of the object.

This method will also copy any complex object and traverse the entire object graph.

 

public static T DeepClone(this T obj)
{
  using (var ms = new MemoryStream()) {
    var bf = new BinaryFormatter();
    bf.Serialize(ms, obj);
    ms.Position = 0;
    return (T)bf.Deserialize(ms);
  }
}