我有一个目标类,看起来像这样:
public class CustomerAddressSummary
{
public string StateTxt { get; set; }
public string AddrLn1 { get; set; }
public string AddrLn2 { get; set; }
public string Phn { get; set; }
public string HomePhnNbr { get; set; }
public string MobilePhnNbr { get; set; }
public string WorkPhnNbr { get; set; }
public string EmailAddr { get; set; }
}
和源类:
public class CustomerAddressSummaryObj
{
public ADDRESS Address { get; set; }
public List<COMMUNICATION> Communications { get; set; }
public string StateTxt { get; set; }
}
以下是映射:
CreateMap<CustomerAddressSummaryObj, CustomerAddressSummary>()
.ForMember(dest => dest.StateTxt, opt => opt.MapFrom(src => src.StateTxt))
.ForMember(dest => dest.AddrLn1, opt => opt.MapFrom(src => src.Address.ADDRLN1))
.ForMember(dest => dest.AddrLn2, opt => opt.MapFrom(src => src.Address.ADDRLN2));
CreateMap<COMMUNICATION, CustomerAddressSummary>()
.ForMember(dest => dest.Phn,
opt => opt.MapFrom(src => src.TYPECD == Constant.CommunicationTypeCode.Main ? src.DETAILS : null))
.ForMember(dest => dest.EmailAddr,
opt => opt.MapFrom(src => src.TYPECD == Constant.CommunicationTypeCode.Email ? src.DETAILS : null))
.ForMember(dest => dest.HomePhnNbr,
opt => opt.MapFrom(src => src.TYPECD == Constant.CommunicationTypeCode.Home ? src.DETAILS : null))
.ForMember(dest => dest.MobilePhnNbr,
opt => opt.MapFrom(src => src.TYPECD == Constant.CommunicationTypeCode.Mobile ? src.DETAILS : null))
.ForMember(dest => dest.WorkPhnNbr,
opt => opt.MapFrom(src => src.TYPECD == Constant.CommunicationTypeCode.Work ? src.DETAILS : null));
实施:
var customerAddress = _mapper.Map<CustomerAddressSummary>(customerAddressSummaryObj);
这将填充除COMMUNICATION
之外的所有信息。所以我尝试了这样的事情:
var customerAddress = _mapper.Map<CustomerAddressSummary>(customerAddressSummaryObj)
.Map(customerAddressSummaryObj.Communications,_mapper);
public static TDestination Map<TSource, TDestination>(this TDestination destination, TSource source, IMapper mapper)
{
return source == null ? destination : mapper.Map(source, destination);
}
但是,这也不起作用,并引发异常。知道我在这里缺少什么吗?
答案 0 :(得分:0)
我能够使用Linq
CreateMap<CustomerAddressSummaryObj, CustomerAddressSummary>()
.ForMember(dest => dest.EmailAddr, opt => opt.MapFrom((src,dest) => src.Communications
.FirstOrDefault(x => x.TYPECD == Constant.CommunicationTypeCode.Email)?.DETAILS))