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

为君一笑 提交于 2020-01-03 09:03:18

问题


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.


回答1:


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.

I hope it helps.



来源:https://stackoverflow.com/questions/46725911/automapper-map-single-object-with-list-of-objects-inside-to-just-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!