我正在将一个平面对象映射到一个复杂对象,并且该复杂对象具有相同类的子对象。如何告诉AutoMapper根据复杂对象的哪个子对象,使用从平面对象类到子对象类的不同映射。请参见示例代码,其中平面对象有两个地址,复杂对象有两个地址对象(相同的类),但是每个对象都需要使用源对象的不同字段。
有一种解决方案,可以首先使用一个AutoMaper配置来初始映射一个地址,然后我们切换到另一个AutoMapper配置来映射第二个地址。但是,已映射器对象被注入,这不是可行的解决方案。
public class FlatObject
{
public string OwnerName;
public string OwnerAddress1;
public string OwnerAddress2;
public string OwnerCity;
public string OwnerZip;
public string PartnerName;
public string PartnerAddress1;
public string PartnerAddress2;
public string PartnerCity;
public string partnerZip;
public string CompanyName;
}
public class ComplexObject
{
public string OwnerName;
public Address OwnerAdress;
public string PartnerName;
public Address PartnerAddress;
public string CompanyName;
}
public class Address
{
public string Address1;
public string Address2;
public string City;
public string zip;
}
public class SampleProfile : Profile
{
protected override void Configure()
{
CreateMap<FlatObject, Address>()
.ForMember(m => m.Address1, o => o.MapFrom(src => src.OwnerAddress1))
.ForMember(m => m.Address2, o => o.MapFrom(src => src.OwnerAddress2))
.ForMember(m => m.City, o => o.MapFrom(src => src.OwnerCity))
.ForMember(m => m.zip, o => o.MapFrom(src => src.OwnerZip));
CreateMap<FlatObject, ComplexObject>()
.ForMember(m => m.OwnerName, o => o.MapFrom(src => src.OwnerName))
.ForMember(m => m.PartnerName, o => o.MapFrom(src => src.PartnerName))
.ForMember(m => m.CompanyName, o => o.MapFrom(src => src.CompanyName))
.ForMember(m => m.OwnerAdress, o => o.MapFrom(src => src))
.ForMember(m => m.PartnerAddress, ?????);
}
}