Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using AutoMapper to create an object, which represents a result of comparing two other objects

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?

like image 386
Liel Avatar asked Oct 28 '25 05:10

Liel


1 Answers

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);
like image 75
James Avatar answered Oct 30 '25 21:10

James



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!