Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automapper: Map single object with list of objects inside to just list

Tags:

c#

automapper

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.

like image 353
user348173 Avatar asked Oct 13 '17 08:10

user348173


Video Answer


1 Answers

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.

like image 171
dbvega Avatar answered Oct 10 '22 23:10

dbvega