源类:
public class ApplicationDriverFormVM
{
public ApplicationDriverAddressFormVM PresentAddress { get; set; }
public List<ApplicationDriverAddressFormVM> PreviousAddresses { get; set; }
}
public class ApplicationDriverAddressFormVM
{
[Required]
[StringLength(256)]
[Display(Name = "Address")]
public string Address { get; set; }
[Required]
[StringLength(256)]
[Display(Name = "City")]
public string City { get; set; }
//.....
}
目的地类:
public class ApplicationDriverDomain
{
public List<ApplicationDriverAddressDomain> Addresses { get; set; }
}
public class ApplicationDriverAddressDomain
{
public int Id { get; set; }
public string Address { get; set; }
public string City { get; set; }
//....
public bool IsPresentAddress { get; set; }
}
因此,我想将presentAddress(一个对象)和先前的附加绘制(集合)映射到地址属性(集合),其中每个元素具有ISPresentAddress属性,如果绘制了PresentAddress,则该元素应该为真,并且对于以前的AdadDress映射了forse。我尝试编写这样的地图基本规则:
CreateMap<ViewModels.ApplicationDriverFormVM, ApplicationDriverDomain>();
CreateMap<ViewModels.ApplicationDriverAddressFormVM, ApplicationDriverAddressDomain>();
当然,它无法正常工作。如何处理?
这可以使用ForMember
扩展方法来完成。
这是获取想要的东西的快速而肮脏的方法。它制作了一个新的ApplicationDriverAddressFormVM
列表要映射,但是如果您探索文档,则可以找到更优雅的东西。
Mapper.CreateMap<ApplicationDriverFormVM, ApplicationDriverDomain>()
.ForMember(dest => dest.Addresses, opt => opt.MapFrom(src => src.PreviousAddresses.Union(new List<ApplicationDriverAddressFormVM>() { src.PresentAddress })));
Mapper.CreateMap<ApplicationDriverAddressFormVM, ApplicationDriverAddressDomain>();
进一步调查后,我发现了以下方法。它使用ResolveUsing
选项。同样,这很粗糙,只使用我发现的第一个功能。您应该进一步探索IMemberConfigurationExpression
接口,并查看您拥有的其他选项
Mapper.CreateMap<ApplicationDriverFormVM, ApplicationDriverDomain>()
.ForMember(dest => dest.Addresses, opt => opt.ResolveUsing(GetAddresses));
...
static object GetAddresses(ApplicationDriverFormVM src)
{
var result = Mapper.Map<List<ApplicationDriverAddressDomain>>(src.PreviousAddresses);
foreach(var item in result)
{
item.IsPresentAddress = false;
}
var present = Mapper.Map<ApplicationDriverAddressDomain>(src.PresentAddress);
present.IsPresentAddress = true;
result.Add(present);
return result;
}