Automapper 5有可能将许多属性映射到一个列表中吗?

本文关键字:一个 列表 有可能 许多 属性 映射 Automapper | 更新日期: 2023-09-27 18:03:23

我的母语不是英语,所以如果有重复的问题,我很抱歉。

我有一个请求类:
class input {
  Car mainCar,
  List<Car> otherCars
}

映射到:

class mapped {
  List<CarDTO> cars
}

与选项类似,当映射从mainCar设置carType=EnumCarType。主,否则enumcartype。other。

这将与Automapper 5工作吗?

Automapper 5有可能将许多属性映射到一个列表中吗?

这段代码应该可以让您入门,尽管有些细节不清楚,而且我在这里没有编译器:它做出了合理的假设,并使用了自定义类型转换器。注册后,无论何时从输入对象映射到映射对象,都会使用它进行实际的转换。

public class CarTypeConverter : ITypeConverter<input, mapped> 
{
    public mapped Convert(ResolutionContext context) 
    {
        // get the input object from the context
        input inputCar = (input)context.SourceValue;
        // get the main car        
        CarDTO mappedMainCar = Mapper.Map<Car, CarDTO>(input.mainCar);
        mappedMainCar.carType = EnumCarType.Main;
        // create a list with the main car, then add the rest
        var mappedCars = new List<CarDTO> { mappedMainCar };
        mappedCars.AddRange(Mapper.Map<Car, CarDTO>(inputCar.otherCars));
        return new mapped { cars = mappedCars };
    }
}
// In Automapper initialization
mapperCfg.CreateMap<input, mapped>().ConvertUsing<CarTypeConverter>();
mapperCfg.CreateMap<Car, CarDTO>()
           .ForMember(dest => dest.carType, opt => EnumCarType.Other);