2

How can I make a deep copy of an object graph that has been loaded by Entity Framework Code First with proxies enabled?

I'm using code like this:

    static public T DeepCopy<T>(T obj)
    {
        BinaryFormatter s = new BinaryFormatter();
        using (MemoryStream ms = new MemoryStream())
        {
            s.Serialize(ms, obj);
            ms.Position = 0;
            T t = (T)s.Deserialize(ms);

            return t;
        }
    }

However, the serializer complains correctly that the proxy types are not known types.

UPDATE

Using DataContractSerializer with ProxyContractResolver does not work because my class is decorated with DataContract(IsReference = true).

See

Serialize EF Proxy when POCO has IsReference = true Attribute

Community
  • 1
  • 1
Eric J.
  • 147,927
  • 63
  • 340
  • 553
  • Try to use `DataContractSerializer` and set its `DataContractResolver` property to [`ProxyDataContractResolver`](http://msdn.microsoft.com/en-us/library/system.data.objects.proxydatacontractresolver.aspx) instance. – Ladislav Mrnka Jul 10 '12 at 08:34
  • Unfortunately, I need the IsReference attribute on many classes in the object graph and the EF proxy generator does not seem to respect that attribute. – Eric J. Jul 10 '12 at 17:13
  • I will have to try this myself tomorrow because I thought that using `ProxyDataContractResolver` should instruct serializer to use the original POCO type instead of the proxy. In such case it should correctly recognize and handle your `IsReference` settings. – Ladislav Mrnka Jul 10 '12 at 21:45
  • Check this [article](http://blogs.msdn.com/b/adonet/archive/2010/01/05/poco-proxies-part-2-serializing-poco-proxies.aspx). It is old but it discusses problem of serialization with both `DataContractSerializer` and `BinaryFormatter`. – Ladislav Mrnka Jul 10 '12 at 21:56
  • Thanks. I solved my original problem by reworking my approach to what is cached vs. what is loaded per web request. I'm now loading more than would be strictly necessary, but at least it works and performance is adequate. – Eric J. Jul 11 '12 at 18:29

0 Answers0