1

I'm trying to have a deepcopy of an entity record so that I can compare it at a later time.

I've tried multiple DeepCopy Codes but they are producing this error.

var oldAddress = DeepClone(_entity.Addresses.Where(x => x.Id == 
addressDTO.Id).FirstOrDefault());


"System.Data.Entity.DynamicProxies.....is not marked as serializable."

Code used

public static T DeepClone<T>(this T obj)
{
    using (var ms = new MemoryStream()) {
        var bf = new BinaryFormatter();
        bf.Serialize(ms, obj);
        ms.Position = 0;
        return (T)bf.Deserialize(ms);
    }
}
Tharif
  • 13,794
  • 9
  • 55
  • 77
Master
  • 2,038
  • 2
  • 27
  • 77

2 Answers2

0

The compiler is telling you that this code is not going to work. The entity has some dynamic proxies in it, which can't be serialized.

Your DeepClone function is using serialization and deserialization to clone the object - and you are not able to serialize these proxies.

I didn't try to clone Entity framework objects, so I don't know if this will work - but with NHibernate you can access the nested objects and those proxy objects are replaced with the actual objects. So this MAY work. But it is pretty hacky.

A better solution would be to create an object without entity framework and copy the data you need to these objects. There are some solutions to copy the data from an Entity framework object to the plain object easily.

I am using Glue for this (https://glue.codeplex.com/).

Another solution would be Automapper (https://github.com/AutoMapper/AutoMapper)

These newly created objects can be serialized, stored, compared and cloned easily.

bernhardrusch
  • 11,670
  • 12
  • 48
  • 59
0

disable proxy creation. also you need to add this:

bf.Context = new StreamingContext(StreamingContextStates.Clone);
Amit Kumar Ghosh
  • 3,618
  • 1
  • 20
  • 24