可以使用元组和创建一个继承自Automapper的Abstract TypeConverter类的自定义类型转换器来完成此操作。
假设您有一个源类和目标类:
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public override string ToString()
{
return string.Format("Firstname: {0}, Lastname: {1}", FirstName, LastName);
}
}
然后,您可以构建自定义的转换器类型,如下所示:
public class CustomerPersonConverter : TypeConverter<Tuple<Person, Person>, Person>
{
protected override Person ConvertCore(Tuple<Person, Person> source)
{
var orginalValues = source.Item1;
var updatedValues = source.Item2;
var result = new Person
{
FirstName = string.IsNullOrEmpty(updatedValues.FirstName) ? orginalValues.FirstName : updatedValues.FirstName,
LastName = string.IsNullOrEmpty(updatedValues.LastName) ? orginalValues.LastName : updatedValues.LastName
};
return result;
}
}
这可以像这样使用
var orginal = new Person() {FirstName = "Clifford", LastName = "Mayson"};
var updated = new Person() {FirstName = "Cliff"};
Mapper.CreateMap<Tuple<Person, Person>, Person>().ConvertUsing<CustomerPersonConverter>();
var result = Mapper.Map<Person>(new Tuple<Person, Person>(orginal, updated));
Console.WriteLine(result);
这将导致保留原始的姓氏值(因为更新中缺少了该值),但更新名字值。
Firstname: Cliff, Lastname: Mayson
Mapper.Map
应该返回UserDetails
还是UserSession
? - Chris Farmer