I have the following dto object:
public class PriceDto
{
public string Ticker {get; set;}
public double Open {get; set;}
public double Close {get; set;}
}
The 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;}
}
In result, I want to get collection of PriceDto
objects. I know how to map Ticker
property. But, I have no idea how to map Prices
correctly:
CreateMap<RemoteData, PriceDto>()
.ForMember(d => d.Ticker, opt => opt.MapFrom(s => s.Security.Ticker));
Also, Automapper can't find the configuration because I have single RemoteData
, but I want to get IList<PriceDto>
:
var json = await rangeUrl.GetJsonAsync<RemoteData>();
var dtos = _mapper.Map<IList<PriceDto>>(json);
For the workaround, I created map from Prices
to PriceDto
instead of RemoteData
and then just use foreach
to assign Ticker
. But, I want to undertand how to do it with automapper.
A good approach for this case is to use the .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()
);
});
...
For more information read about custom type converters.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With