0

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.

Andrew Whitaker
  • 124,656
  • 32
  • 289
  • 307

1 Answers1

0

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)));
Andrew Whitaker
  • 124,656
  • 32
  • 289
  • 307
  • Thanks for the quick reply. I have an add-on question to this. With your solution I am able to map all the three type of drivers into one collection. My destination object has a property called DriverType which helps in identifying the type of driver. (Unreported/Other/etc) In the above code, how i can set the destination property based on the collection I am adding. for eg: i have to hard code ReportType= Other for OtherDriver collection items ReportType = Unreported for UnreportedDriver collection item. Thanks in advance – Sandeep Pinniti May 30 '12 at 13:26
  • @SandeepPinniti: That seems like a little bit of a harder requirement. You may have to use a custom resolver instead... – Andrew Whitaker May 30 '12 at 13:38