关于AutoMapper的新问题
员工模型对象。
public class Employee {
public string FirstName { get; set; }
public string LastName { get; set; }
public decimal HourlyRate { get; set; }
public List<string> EmailAddresses { get; set; }
}
Dto对象:
public class UpdateEmployeeDetailsDto {
public decimal HourlyRate { get; set; }
public string EmailAddress1 { get; set; }
public string EmailAddress2 { get; set; }
}
我想将DTO映射到Employee对象,并将EmailAddress1和EmailAddress2转换为List。
我在谷歌和SO上搜索过这种类型的东西,但我发现的例子我一直无法将它们转化为工作代码。
帮忙吗?
使用AfterMap
来提供自定义映射(在您的例子中是从属性创建列表):
Mapper.CreateMap<UpdateEmployeeDetailsDto, Employee>()
.AfterMap((dto, e) => e.EmailAddresses = new List<string>() {
dto.EmailAddress1,
dto.EmailAddress2
});
除了@lazyberezovsky所说的,您还可以创建一个自定义解析器:
public class CustomResolver : ValueResolver<UpdateEmployeeDetailsDto, List<string>>
{
protected override List<string> ResolveCore(UpdateEmployeeDetailsDto source)
{
return new List<string> { source.EmailAddress1, source.EmailAddress2 }
}
}
Mapper.CreateMap<UpdateEmployeeDetailsDto, Employee>()
.ForMember(dest => dest.EmailAddresses, opt => opt.ResolveUsing<CustomResolver>());
有什么意义?你可以让它更通用,用它来解决Value1
, Value2
, Value3
…ValueN
被映射到List<ValueType> Values