简体   繁体   中英

How to use Automapper toavoid foreach for complex structure

I am trying to map source and destination instances using automapper,

I have a sample code which i have created. Line number 82 i am trying to change anduse automapper. Is it possible to use automapper there.

https://dotnetfiddle.net/bzp9H7

Yes, you can map a list put after taking a look at your code I don't think you need a list or array for destinationArray field. If you need to use it as an array all you have to do is adding.First() after destinationArray.

  public static IMapper CreateGroboBookingMapper()
    {
        var config = new MapperConfiguration(cfg =>
        {
            cfg.AllowNullDestinationValues = true;

            cfg.CreateMap<Booking, DestinationBooking>()
        .ForMember(dest => dest.processTypeField, opt => opt.MapFrom(src => src.processTypeField))
        .ForMember(dest => dest.travelDate, opt => opt.MapFrom(src => src.Trip.Voyages.FirstOrDefault().DepartureDate))
        .ForMember(dest => dest.destinationArrayField, opt => opt.MapFrom(a => new destinationArray() 
            {
              // Here you can add destinationArray models parameters
            arrivalStationIdField= a.Trip.Voyages.Select(x => x.arrivalStationId).FirstOrDefault().ToString(),
            extraField = *************
        }));
       
        });

        return config.CreateMapper();
    }

And here is the result from debugging, as I've tried one value:

Debugging Result

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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