如何将稍微复杂的场景从->映射到成员场景

时间:2019-10-23 06:40:57

标签: c# .net .net-core automapper

我有一个CarDtoCar域对象。 汽车有司机清单。

public class Car
{
    public int Id {get; set; }
    public int Name {get; set; }
    public ICollection<Driver> Drivers {get; set; }
}


public class CarVM
{
    public int Id {get; set; }
    public int Name {get; set; }
    public string DriverBadge {get; set; }
    public string[] Drivers {get; set; }
}

我正在尝试使用AutoMapper映射此对象

 CreateMap<CarVM, Car>()
      .ForMember(dest => dest.Name, opts => opts.MapFrom(src => src.Name))
      .ForMember(dest => dest.Drivers, opts => {
      ... how to map here?
})

1 个答案:

答案 0 :(得分:1)

您要做的就是将string[]映射到List<>。只需使用以下

 CreateMap<CarVM, Car>()
      .ForMember(dest => dest.Name, opts => opts.MapFrom(src => src.Name))
      .ForMember(dest => dest.Drivers, opts => opts.MapFrom(s=> s.Drivers.ToList()))
});

更多信息-Automapper Lists & Arrays