Collection overriding when mapping two collections of same type using Automapper

761 views Asked by At

I have my classes defined as below

Source {

    public List<Driver> UnreportedDrivers { get; set; }  // count 1

    public List<Driver> LendingLossDrivers { get; set; }  // count 2

    public List<Driver> OtherDrivers { get; set; } // count 1

}

Destination {

    public List<Driver> Drivers { get; set; }  // expected count = 4 after mapping

}

I have to map from source to destination. I have to merge all the collections from source and map them to Destination.

I have defined my mapping as below. But this piece of code doesn't help me out. Instead of merging all the collections, it only maps the last one (UnreportedDrivers) overriding the top ones.

AutoMapper.Mapper.CreateMap<ServiceModel.MacReconciliationResponse, MacProcessContext>()
                .ForMember(destination => destination.Drivers, source => source.MapFrom(s => s.OtherDrivers))
                .ForMember(destination => destination.Drivers, source => source.MapFrom(s => s.LendingLossDrivers))
                .ForMember(destination => destination.Drivers, source => source.MapFrom(s => s.UnreportedDrivers));

Please help me in this scenario.

Thanks in advance.

1

There are 1 answers

2
Andrew Whitaker On

I would simply .Concat each list you'd like to map in one .ForMember call:

Mapper.CreateMap<Source, Destination>()
    .ForMember(dest => dest.Drivers, opt => opt.MapFrom(src => src.LendingLossDrivers
        .Concat(src.OtherDrivers)
        .Concat(src.UnreportedDrivers)));