自动映射器:将单个对象及其内部的对象列表映射到列表中

编程入门 行业动态 更新时间:2024-10-24 20:19:05
本文介绍了自动映射器:将单个对象及其内部的对象列表映射到列表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有以下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() ); }); ...

有关更多信息,了解自定义类型转换器.

希望对您有帮助.

更多推荐

自动映射器:将单个对象及其内部的对象列表映射到列表中

本文发布于:2023-11-26 17:26:46,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1634505.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:对象   列表   列表中   映射器

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!