0
我得到了如下的類結構,並且創建了映射結構,但它不像預期的那樣工作。如何使用自動映射器將單個對象屬性映射到複雜類型的對象數組
public class ResponseHeader
{
public ResHeader ResHeader { get; set; }
}
public class ResHeader
{
public ServiceResStatus ServiceResStatus { get; set; }
public Error[] Errors { get; set; }
}
public class Error
{
public string ErrorCode { get; set; }
public string ErrorDesc { get; set; }
public string Source { get; set; }
}
public class ServiceResStatus
{
public string ServiceResCode { get; set; }
public string ServiceResDesc { get; set; }
public System.DateTime ServiceRespDateTime { get; set; }
public string ServiceUniqueRefNo { get; set; }
}
public class ExceptionInformation
{
public string Code { get; set; }
public string Description { get; set; }
public string Source { get; set; }
}
我想映射ExceptionInformation屬性到ResponseHeader。我總是得到ResponseHeader dto爲null。
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<ExceptionInformation, ResponseHeader>();
cfg.CreateMap<ExceptionInformation, ResHeader>()
.ForMember(d => d.Errors, opts => opts.ResolveUsing(src => new Error() {ErrorCode = src.Code}))
.ForMember(d => d.Errors, opts => opts.ResolveUsing(src => new Error() {ErrorDesc = src.Description}))
.ForMember(d => d.Errors, opts => opts.ResolveUsing(src => new Error() {Source = src.Code}))
.ForMember(d => d.ServiceResStatus, opts => opts.Ignore());
cfg.CreateMap<ExceptionInformation, ServiceResStatus>()
.ForMember(d => d.ServiceResCode, opts => opts.MapFrom(src => src.Code))
.ForMember(d => d.ServiceResDesc, opts => opts.MapFrom(src => src.Description))
.ForMember(d => d.ServiceRespDateTime, opts => opts.MapFrom(src => DateTime.Now))
.ForMember(d => d.ServiceUniqueRefNo, opts => opts.Ignore());
});
var mapper = config.CreateMapper();
var info = new ExceptionInformation()
{
Code = "ERR01",
Description = "Error",
Source = "Oven"
};
ResponseHeader dto = mapper.Map<ResponseHeader>(info);
任何工作解決方案讚賞。