3

假设以下类:

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

我想AutoMapper用来比较两个MyEntity对象,并创建一个MyEntity只包含两个对象之间差异的新对象。相等的属性将null在新对象中产生一个值。

例如,我想要以下几行:

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

产生以下diffEntity值:

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

最终目标是使客户端移动应用程序能够将仅包含对实体所做更改的 DTO 发送到 ASP.NET MVC WebAPI 服务器应用程序。

请假设我有许多需要相同处理的实体类,并且我想避免为每次比较手动编写属性名称。

是否可以?

4

1 回答 1

4

这是可能的,您需要创建一个自定义转换器。也许使用这个问题中的表达式树: 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;
  }
}

一旦你有了这个,你可以使用以下方法将它附加到你的 AutoMapper 上:

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

然后你可以使用通常的模式:

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

Mapper.Map(originalObject , modifiedObject);

// Now modifiedObject contains the differences.

myService.Post(modifiedObject);
于 2013-10-18T12:06:56.413 回答