Search code examples
c#entity-framework-6postsharpserializable

c# comparing objects without creating dto


Currently I am creating a DTO of an object to compare new and old values. It was fine when it was one object, but in the future that's going to change. I tried creating an extension method to serialize and deserialize for a deep copy, but PostSharp is throwing an error.

Type 'PostSharp.Patterns.Model.NotifyPropertyChanged.ChangeTracking.ChildPropertyChangedProcessor' in Assembly 'PostSharp.Patterns.Model, Version=4.2.28.0, Culture=neutral, PublicKeyToken=e7f631e6ce13f078' is not marked as serializable. (SerializationException)

Here is my extension method and the error is being thrown at formatter.Serialize(stream, source).

public static T Clone<T>(this T source)
{
    if (!typeof(T).IsSerializable)
    {
        return default(T);
    }

    if (ReferenceEquals(source, null))
    {
        return default(T);
    }

    var formatter = new BinaryFormatter();
    Stream stream = new MemoryStream();
    using (stream)
    {
        formatter.Serialize(stream, source);
        stream.Seek(0, SeekOrigin.Begin);
        return (T) formatter.Deserialize(stream);
    }
}

Is there a way to fix this error or do I have to do this another way? If I do have to find another way what approach should I take?


Solution

  • You could use AutoMapper for this as well: (Every app should use it anyway, so what's the harm?)

    var clone = new Poco();
    Mapper.CreateMap<Poco, Poco>();
    Mapper.Map<Poco, Poco>(source, clone);