AutoMapper(六)

简介:

List和数组

AutoMapper只要求元素类型的配置而不要求可能会用到的任何数组或者list类型。比如,我们有一个简单的源和目标类型:

public class Source{    public int Value { get; set; }}public class Destination{    public int Value { get; set; }}

支持所有的基本泛型集合,代码如下:

复制代码
class Program{    static void Main(string[] args)    {        Mapper.CreateMap<Source, Destination>();        var sources = new[]        {            new Source() {Value = 1},            new Source() {Value = 2},            new Source() {Value = 3},        };        IEnumerable<Destination> iEnumerableDests= Mapper.Map<IEnumerable<Destination>>(sources);        ICollection<Destination> iCollectionDests= Mapper.Map<ICollection<Destination>>(sources);        IList<Destination> iListDests= Mapper.Map<IList<Destination>>(sources);        List<Destination> listDests= Mapper.Map<List<Destination>>(sources);        Destination[] destsArr= Mapper.Map<Destination[]>(sources);        //这里只举两个例子,其他集合同理        foreach (var dest in iCollectionDests)        {            Console.Write(dest.Value+",");        }        Console.WriteLine();        foreach (var dest in destsArr)        {            Console.Write(dest.Value + ",");        }        Console.Read();    }}
复制代码

以上代码是集合和集合之间的映射,但是映射的配置CreateMap方法中只是配置的是类型之间的映射,而没有设计任何集合类型。

测试结果如下,可见集合之间映射成功:

image

具体来说,支持的源集合类型包括:

  • IEnumerable
  • IEnumerable<T>
  • ICollection
  • ICollection<T>
  • IList
  • IList<T>
  • List<T>
  • Arrays

集合中的多态元素类型

很多时候,在我们的源和目标类型中可能有一个类型层次关系。AutoMapper支持多态数组和集合,因此如果发现派生的源或者目标类型,就会使用它们。

public class ParentSource{    public int Value1 { get; set; }}public class ChildSource : ParentSource{    public int Value2 { get; set; }}public class ParentDestination{    public int Value1 { get; set; }}public class ChildDestination : ParentDestination{    public int Value2 { get; set; }}

AutoMapper仍然要求显示配置孩子映射,因为它不能“猜出”具体使用哪一个孩子目标映射。

在Main方法中添加如下代码:

Mapper.Initialize(c =>{    c.CreateMap<ParentSource, ParentDestination>()        .Include<ChildSource, ChildDestination>();    c.CreateMap<ChildSource, ChildDestination>();});var sources = new[]{    new ParentSource(){Value1 = 11},    new ChildSource(){Value2 = 22},    new ParentSource(),};var dests = Mapper.Map<ParentDestination[]>(sources);Console.WriteLine(dests[0]);Console.WriteLine(dests[1]);Console.WriteLine(dests[2]);

测试结果如下:

image

上面我们创建了一个源的数组,其中包含两个ParentSource和一个ChildSource,所以两个ParentSource成功地映射到了ParentDestination,而CreateMap配置中,ParentSource到ParentDestination的映射配置包含了ChildSource到ChildDestination的配置,所以执行Mapper.Map<ParentDestination[]>(sources)的时候,也可以将ChildSource映射到ChildDestination。

映射继承

在派生类中标明继承

上面的代码,是在基类中配置继承的,除此之外,也可以在派生类中配置继承:

//在基类中配置继承 Mapper.Initialize(c => {     c.CreateMap<ParentSource, ParentDestination>()         .Include<ChildSource, ChildDestination>();     c.CreateMap<ChildSource, ChildDestination>(); }); //在派生类中配置继承 Mapper.Initialize(c => {     c.CreateMap<ParentSource, ParentDestination>();     c.CreateMap<ChildSource, ChildDestination>()         .IncludeBase<ParentSource, ParentDestination>(); });

继承映射属性

这里介绍一下额外的复杂性,因为一个属性映射时可以有多种方式。下面是这些源的优先级:

  • 显式映射 (使用.MapFrom())
  • 继承的显式映射 
  • 惯例映射 (通过惯例匹配的属性)
  • 忽略的属性映射

下面来演示一下:

这里还是用上面定义的四个类:Order,OrderDto,PCOrder,MobileOrder:

//领域对象public class Order { }//电脑端订单public class PCOrder : Order{    public string Referrer { get; set; }}//手机订单public class MobileOrder : Order { }//Dtospublic class OrderDto{    public string Referrer { get; set; }}

配置映射的方法使用的是在父类中配置继承映射

//在父类中配置继承映射Mapper.CreateMap<Order, OrderDto>()    .Include<PCOrder,OrderDto>()    .Include<MobileOrder,OrderDto>()    .ForMember(o => o.Referrer, m => m.Ignore());//这里配置了忽略目标属性Referrer的映射Mapper.CreateMap<PCOrder,OrderDto>();Mapper.CreateMap<MobileOrder, OrderDto>();
// 执行映射var order = new PCOrder() { Referrer = "天猫" };var mapped = Mapper.Map<OrderDto>(order);Console.WriteLine(mapped.Referrer);

执行结果如下:

image

注意在我们的映射配置中,我们已经忽略了Referrer(因为Order基类中不存在这个属性),但是在基类的映射中,惯例比忽略的属性有更高的优先级,因而属性仍然得到了映射。





本文转自tkbSimplest博客园博客,原文链接:http://www.cnblogs.com/farb/p/4944018.html,如需转载请自行联系原作者

目录
相关文章
|
安全 虚拟化
GIC规格学习(一)
GIC规格学习(一)
475 0
|
存储 数据可视化 Serverless
使用蒙特卡罗模拟的投资组合优化
在金融市场中,优化投资组合对于实现风险与回报之间的预期平衡至关重要。蒙特卡罗模拟提供了一个强大的工具来评估不同的资产配置策略及其在不确定市场条件下的潜在结果。
656 1
|
前端开发
Vue3/React 动态设置 ant-design/icons 图标
Vue3/React 动态设置 ant-design/icons 图标
802 1
|
8月前
|
JSON 监控 API
速卖通商品列表接口(速卖通API系列)
速卖通提供商品列表API,开发者可通过关键词、类目、价格范围等条件获取商品标题、价格、销量等基本信息。使用前需注册开发者账号、创建应用并授权获取access_token。Python示例代码展示了如何调用接口,返回JSON格式数据,包含商品列表、总数、页码等信息。应用场景包括商品监控、数据分析和个性化推荐。注意API会更新,请参考官方文档。
|
存储 安全 程序员
|
机器学习/深度学习 编解码 自然语言处理
重磅!新增 13 种 Transformer 方法,火速收藏
如今,Transformer 这把火已经烧到了计算机视觉领域,可以说成为今年最大的热点。本着全心全意为社区服务的精神,OpenMMLab 当然不会对此无动于衷。 为了方便大家研究学习,我们基于 MMCV ,在OpenMMLab 6个方向的 repo 中复现了 13 种基于 Transformer 的方法,快来看看有没有你需要的吧。
997 0
重磅!新增 13 种 Transformer 方法,火速收藏
|
供应链 数据挖掘
数据分析五大指标分类
数据分析中常见的指标分类方法
|
机器学习/深度学习 弹性计算 Cloud Native
阿里云神龙获2023年度CCF技术科技进步一等奖
阿里云神龙获2023年度CCF技术科技进步一等奖
581 0
|
安全 网络安全 数据安全/隐私保护
网络安全与信息安全:保护我们的数字生活
【5月更文挑战第31天】在数字化时代,网络安全和信息安全已经成为我们生活中不可或缺的一部分。本文将深入探讨网络安全漏洞、加密技术以及安全意识的重要性,帮助读者了解如何保护自己的数字信息免受网络攻击。
|
机器学习/深度学习 算法
大模型如何实现对股票的未来走势预测?
这是一个很好的问题。目前,有很多方法可以预测股票价格,其中一种是使用机器学习算法来预测未来的股票价格。这些算法从平均和线性回归等简单的算法开始,然后转自动ARIMA和LSTM等高级技术。
1425 0