Automapper: map a single object to a list of objects within the entire list

I have the following dto object:

public class PriceDto { public string Ticker {get; set;} public double Open {get; set;} public double Close {get; set;} } 

Source objects:

 public class RemoteData { public Security Security { get; set; } public IList<Prices> Prices{ get; set; } } public class Security { public string Ticker {get; set;} } public class Prices { public double Open {get; set;} public double Close {get; set;} } 

As a result, I want to get a collection of PriceDto objects. I know how to map the Ticker property. But I do not know how to correlate Prices correctly:

 CreateMap<RemoteData, PriceDto>() .ForMember(d => d.Ticker, opt => opt.MapFrom(s => s.Security.Ticker)); 

In addition, Automapper cannot find the configuration, because I have one RemoteData , but I want to get IList<PriceDto> :

 var json = await rangeUrl.GetJsonAsync<RemoteData>(); var dtos = _mapper.Map<IList<PriceDto>>(json); 

For a workaround, I created a map from Prices to PriceDto instead of RemoteData , and then just use foreach to assign a Ticker . But I want to take on the task of doing this with automapper.

+5
source share
1 answer

A good approach for this case is to use .ConvertUsing .

 ... Mapper.Initialize(cfg => { cfg.CreateMap<RemoteData, List<PriceDto>>() .ConvertUsing(source => source.Prices?.Select(p => new PriceDto { Ticker = source.Security?.Ticker, Open = p.Open, Close = p.Close }).ToList() ); }); ... 

Read about specialized converters for more information.

Hope this helps.

+2
source

Source: https://habr.com/ru/post/1272588/


All Articles