我有以下dto对象:
public class PriceDto { public string Ticker {get; set;} public double Open {get; set;} public double Close {get; set;} }源对象:
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;} }结果,我想获取PriceDto对象的集合.我知道如何映射Ticker属性.但是,我不知道如何正确映射Prices:
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));此外,由于我只有一个RemoteData,所以Automapper无法找到配置,但是我想获取IList<PriceDto>:
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);对于解决方法,我创建了从Prices到PriceDto而不是RemoteData的映射,然后仅使用foreach分配Ticker.但是,我想了解如何使用自动映射器.
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.
推荐答案在这种情况下,一种好的方法是使用.ConvertUsing.
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() ); }); ...有关更多信息,了解自定义类型转换器.
希望对您有帮助.
更多推荐
自动映射器:将单个对象及其内部的对象列表映射到列表中
发布评论