假设下面的类:
public class MyEntity
{
public string FirstName;
public string LastName;
}
我想使用AutoMapper比较两个MyEntity对象,并创建一个仅包含两个对象之间差异的新MyEntity对象.相等的属性将在新对象中产生空值.
例如,我想要以下几行:
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服务器应用程序.
请假设我有许多需要相同处理的实体类,并且我想避免为每个比较手动编写属性名称.
可能吗?
解决方法:
这是可能的,您可能要创建一个自定义Converter.
也许使用此问题中的表达式树:
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);