0

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.

Will that work with Automapper 5?

Leszek P
  • 1,807
  • 17
  • 24

1 Answers1

2

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);
stuartd
  • 70,509
  • 14
  • 132
  • 163