返回总目录


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方法中只是配置的是类型之间的映射,而没有设计任何集合类型。

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

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

  • 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]);

测试结果如下:

上面我们创建了一个源的数组,其中包含两个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 { } //Dtos

public 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);

执行结果如下:

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

AutoMapper(六)的更多相关文章

  1. 一步一步创建ASP.NET MVC5程序[Repository+Autofac+Automapper+SqlSugar](六)

    前言 大家好,我是Rector 又是星期五,很兴奋,很高兴,很high...啦啦啦... Rector在图享网又和大家见面啦!!!上一篇<一步一步创建ASP.NET MVC5程序[Reposit ...

  2. DTO学习系列之AutoMapper(六)----EntityFramework和AutoMapper的婚后生活

    写在前面 我到底是什么? 越界的可怕 做好自己 后记 文章标题主要关键字:mapping DTOs to Entities,注意并不是“Entities to DTOs”,表示实体对象到DTO的转换, ...

  3. 【道德经】漫谈实体、对象、DTO及AutoMapper的使用

    写在前面 实体和值对象 实体和对象 故常无欲以观其妙,常有欲以观其徼 初始实体和演化实体 代码中的DTO AutoMapper实体转换 后记 实体(Entity).对象(Object).DTO(Dat ...

  4. C#进阶系列——DDD领域驱动设计初探(五):AutoMapper使用

    前言:前篇搭建了下WCF的代码,就提到了DTO的概念,对于为什么要有这么一个DTO的对象,上章可能对于这点不太详尽,在此不厌其烦再来提提它的作用: 从安全上面考虑,领域Model都带有领域业务,让Cl ...

  5. C#进阶系列——DDD领域驱动设计初探(六):领域服务

    前言:之前一直在搭建项目架构的代码,有点偏离我们的主题(DDD)了,这篇我们继续来聊聊DDD里面另一个比较重要的知识点:领域服务.关于领域服务的使用,书中也介绍得比较晦涩,在此就根据博主自己的理解谈谈 ...

  6. 一步一步创建ASP.NET MVC5程序[Repository+Autofac+Automapper+SqlSugar](七)

    前言 大家好,我依旧是你们的老朋友Rector,很高兴又在周五的时候准时和大家见面. Rector的系列文章[一步一步创建ASP.NET MVC5程序[Repository+Autofac+Autom ...

  7. 8分钟学会使用AutoMapper

    一.什么是AutoMapper与为什么用它. 它是一种对象与对象之间的映射器,让AutoMapper有意思的就是在于它提供了一些将类型A映射到类型B这种无聊的实例,只要B遵循AutoMapper已经建 ...

  8. c# AutoMapper 使用方式和再封装

    安装方式:使用vs自带的nuget管理工具,搜索AutoMapper ,选择第一个安装到你的项目即可. 我从网上找了一些资料, 参考网址:http://blog.csdn.net/csethcrm/a ...

  9. c# automapper 使用(一)

    一.最简单的用法 有两个类User和UserDto public class User { public int Id { get; set; } public string Name { get; ...

随机推荐

  1. 自己实现一个javascript事件模块

    nodejs中的事件模块 nodejs中有一个events模块,用来给别的函数对象提供绑定事件.触发事件的能力.这个别的函数的对象,我把它叫做事件宿主对象(非权威叫法),其原理是把宿主函数的原型链指向 ...

  2. 【原创分享·微信支付】 C# MVC 微信支付教程系列之扫码支付

    微信支付教程系列之扫码支付                  今天,我们来一起探讨一下这个微信扫码支付.何为扫码支付呢?这里面,扫的码就是二维码了,就是我们经常扫一扫的那种二维码图片,例如,我们自己添 ...

  3. Android Studio —— 重装 HAXM

    Android Studio -- 重装 HAXM 版权声明:本文为博主原创文章,未经博主允许不得转载. 微博:厉圣杰 文中如有纰漏,欢迎大家留言指出. Android SDK 自带模拟器一直以慢.卡 ...

  4. [开发笔记] Graph Databases on developing

    TimeWall is a graph databases github It be used to apply mathematic model and social network with gr ...

  5. javascript动画系列第二篇——磁性吸附

    × 目录 [1]范围限定 [2]拖拽范围 [3]磁性吸附 前面的话 上一篇,我们介绍了元素拖拽的实现.但在实际应用中,常常需要为拖拽的元素限定范围.而通过限定范围,再增加一些辅助的措施,就可以实现磁性 ...

  6. 【手记】注意BinaryWriter写string的小坑——会在string前加上长度前缀length-prefixed

    之前以为BinaryWriter写string会严格按构造时指定的编码(不指定则是无BOM的UTF8)写入string的二进制,如下面的代码: //将字符串"a"写入流,再拿到流的 ...

  7. JQuery实现表格的增加行和删除行

    利用JQuery实现datatables插件的增加和删除行操作 在学习过程中遇到了这个利用JQuery对表格行的增加和删除,特记录下来以供初学者参考. 下面是主要的代码: <meta http- ...

  8. Windows下MySQL无法启动

    问题描述: 从网上下了5.7 的MySQL,在bin目录下执行 start mysqld ,弹出个cmd窗口一闪就没了,也看不清是什么报错.mysqld --install安装了服务,也启动不了.   ...

  9. [Hadoop in Action] 第7章 细则手册

    向任务传递定制参数 获取任务待定的信息 生成多个输出 与关系数据库交互 让输出做全局排序   1.向任务传递作业定制的参数        在编写Mapper和Reducer时,通常会想让一些地方可以配 ...

  10. Linux 权限设置chmod

    Linux中设置权限,一般用chmod命令 1.介绍 权限设置chmod 功能:改变权限命令.常用参数: 1=x(执行权execute) 2=w(写权write) 4=r(读权Read) setuid ...