3

Assume the following class:

public class MyEntity
{
    public string FirstName;
    public string LastName;
}

I would like to use AutoMapper to compare two MyEntity objects, and create a new MyEntity object that contains only the differences between the two objects. Properties that are equal will result a null value in the new object.

for example, the I would like the following lines:

MyEntity entity1 = new MyEntity() { FirstName = "Jon", LastName = "Doh" };
MyEntity entity2 = new MyEntity() { FirstName = "Jon", LastName = "The Great" };
MyEntity diffEntity = Mapper.Map...;   // Compare the two objects using AutoMapper

to result with the following diffEntity values:

{
    FirstName: null,
    LastName: "The Great"
}

The final goal is to enable a client mobile application to send a DTO that contains only the changes made to an entity, to a ASP.NET MVC WebAPI server application.

Please assume that I have many classes of entities which requires the same handling, and I would like to avoid manually writing property names for each comparison.

Is it possible?

Ivan Chaer
  • 6,980
  • 1
  • 38
  • 48
Liel
  • 2,407
  • 4
  • 20
  • 39

1 Answers1

4

This is possible, you would want to create a custom Converter. Perhaps using the Expression Trees from this question: Hows to quick check if data transfer two objects have equal properties in C#?

public class DifferenceConverter<T> : ITypeConverter<T, T>
{
  public T Convert(ResolutionContext context)
  {
  // Code to check each property to see if different, could be done with
  // Reflection or by writing some Dynamic IL.
  // Personally I would use Reflection to generate (then cache) an Expression tree  
  // to compare each object at native speeds..

  return differenceObject;
  }
}

Once you have this you can attach it to you AutoMapper using the following method:

AutoMapper.Mapper.CreateMap<MyEntity, MyEntity>().ConvertUsing<DifferenceConverter<MyEntity>>();

Then you can use the usual pattern:

var originalObject = new MyEntity();
var modifiedObject = new MyEntity();

Mapper.Map(originalObject , modifiedObject);

// Now modifiedObject contains the differences.

myService.Post(modifiedObject);
Community
  • 1
  • 1
James
  • 2,458
  • 3
  • 26
  • 50
  • Sounds promising, thank you for that! I will try it out and be back to this post as soon as I can (might take a few days...) – Liel Oct 18 '13 at 13:37