我如何将 AutoMapper 用于主细节 class

How I use AutoMapper for master detail class

我试图映射 ParentChild 对象,但 Child 映射失败。 我已经配置了 automapper 来识别 master 和 detail class.

这里是我的 class 和 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/result 值是:

update: {Test.Program.MasterDTO}
  details [Icollection]: Count = 0
  id [int] : 1
  masterInfo [string]: "xxxx"

需要你的建议。谢谢 - 极谷

你应该使用这样的 ForMember 方法来映射 child 属性

var config = new MapperConfiguration(cfg =>
{
    cfg.CreateMap<Master, MasterDTO>().ForMember(a => a.details, map => map.MapFrom(src => src.details));
    cfg.CreateMap<Detail, DetailDTO>();
});