我正在尝试映射ParentChild对象,但是Child未能映射。我已经配置了自动映射器以识别主类和详细类。
这里是我的班级和classDTO
public class Master {
public int id {get;set;}
public string masterInfo {get;set;}
public ICollection<Detail> details { get; } = new Collection<Detail>();
}
public class Detail {
public int id {get;set;}
public int masterId {get;set;}
public Master master {get;set;}
public string detailInfo {get;set;}
}
public class MasterDTO {
public int id {get;set;}
public string masterInfo {get;set;}
public ICollection<DetailDTO> details { get; } = new Collection<DetailDTO>();
}
public class DetailDTO {
public int id {get;set;}
public int masterId {get;set;}
public MasterDTO master {get;set;}
public string detailInfo {get;set;}
}
这是我的主程序:
var config = new MapperConfiguration(cfg => {
cfg.CreateMap<Master, MasterDTO>();
cfg.CreateMap<Detail, DetailDTO>();
});
IMapper mapper = config.CreateMapper();
var original1 = new Master { id=1,masterInfo="xxxx",
details = { new Detail {id = 11, masterId = 1, detailInfo="aaaa"},
new Detail {id = 12, masterId = 1, detailInfo="bbbb"}
}};
var update = mapper.Map<Master, MasterDTO>(original1);
和原始值为:
original1: {Test.Program.Master}
details [Icollection]: Count = 2
[0]: {Test.Program.Detail}
detailInfo [string]: "aaaa"
id [int] : 11
master [Master] : null
masterId [int] : 1
[1]: {Test.Program.Detail}
detailInfo [string]: "bbbb"
id [int] : 12
master [Master] : null
masterId [int] : 1
id [int] : 1
masterInfo [string]: "xxxx"
和更新/结果值为:
update: {Test.Program.MasterDTO}
details [Icollection]: Count = 0
id [int] : 1
masterInfo [string]: "xxxx"
需要您的建议。谢谢-Jigu
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Master, MasterDTO>().ForMember(a => a.details, map => map.MapFrom(src => src.details));
cfg.CreateMap<Detail, DetailDTO>();
});