简体   繁体   English

Automapper 5是否可以将许多属性映射到一个列表中?

[英]Is it possible with Automapper 5 to map from many properties into one list?

I am not native English so apologies if there is already duplicated question. 我不是英语母语人士,所以如果已经有重复的问题,我深表歉意。

I have a request class: 我有一个要求课:

class input {
  Car mainCar,
  List<Car> otherCars
}

to be mapped into: 映射到:

class mapped {
  List<CarDTO> cars
}

with option like when mapping from mainCar set carType=EnumCarType.Main, else EnumCarType.Other. 具有从mainCar映射时的选项,设置为carType = EnumCarType.Main,否则为EnumCarType.Other。

Will that work with Automapper 5? 可以在Automapper 5中使用吗?

This code should get you started, though hazy on some details and I don't have a compiler here: it makes reasonable assumptions and uses a custom type converter . 这段代码应该使您入门,尽管在某些细节上比较模糊,并且这里没有编译器:它做出合理的假设并使用自定义类型转换器 When this is registered, it's used to do the actual conversion whenever you map from an input object to a mapped object. 注册此对象后,每当您从输入对象映射到映射对象时,就会使用它进行实际的转换。

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM