假设以下课程:
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服务器应用程序。
请假设我有许多类实体需要相同的处理,我想避免为每次比较手动编写属性名称。
有可能吗?
答案 0 :(得分: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);