【问题标题】:mapping list of objects using automapper使用自动映射器映射对象列表
【发布时间】:2021-10-28 17:04:06
【问题描述】:

我正在使用自动映射器来动态映射对象。

public class CarProfile : Profile
{
    public CarProfile()
    {
        CreateMap<Car, CarVM>();
        CreateMap<CarVM, Car>();
        CreateMap<List<Car>, List<CarVM>>();
        CreateMap<List<CarVM>, List<Car>>();            
    }
}

List<Car> cars = ... get data()...
List<CarVM> vmList = new List<CarVM>();

foreach (var car in cars)
{
    vmList.Add(mapper.Map<Car>(item));
}

这可行,但我想映射列表而不是 foreach 列表中的每个对象,所以我尝试了

 vmList.AddRange(mapper.Map<List<Car>>(cars));

我没有收到异常或错误,但 vmList 中没有对象。 我在这里缺少什么?

【问题讨论】:

    标签: c# .net-core automapper


    【解决方案1】:

    删除List 映射。

    CreateMap<List<Car>, List<CarVM>>();
    CreateMap<List<CarVM>, List<Car>>(); 
    

    您只需要单数映射。
    复数/列表是开箱即用的,请参阅documentation。

    CreateMap<Car, CarVM>();
    CreateMap<CarVM, Car>();
    

    您可能还指:mapper.Map&lt;List&lt;CarVM&gt;&gt;(cars)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-02
      • 1970-01-01
      • 1970-01-01
      • 2020-07-05
      相关资源
      最近更新 更多