一、最简单的用法

有两个类User和UserDto

 1     public class User
2 {
3 public int Id { get; set; }
4 public string Name { get; set; }
5 public int Age { get; set; }
6 }
7
8 public class UserDto
9 {
10 public string Name { get; set; }
11 public int Age { get; set; }
12 }

将User转换成UserDto也和简单

1     Mapper.Initialize(x => x.CreateMap<User, UserDto>());
2 User user = new User()
3 {
4 Id = 1,
5 Name = "caoyc",
6 Age = 20
7 };
8 var dto = Mapper.Map<UserDto>(user);

这是一种最简单的使用,AutoMapper会更加字段名称去自动对于,忽略大小写。

二、如果属性名称不同

将UserDto的Name属性改成Name2

 1     Mapper.Initialize(x =>
2 x.CreateMap<User, UserDto>()
3 .ForMember(d =>d.Name2, opt => {
4 opt.MapFrom(s => s.Name);
5 })
6 );
7
8 User user = new User()
9 {
10 Id = 1,
11 Name = "caoyc",
12 Age = 20
13 };
14
15 var dto = Mapper.Map<UserDto>(user);

三、使用Profile配置

自定义一个UserProfile类继承Profile,并重写Configure方法

 1     public class UserProfile : Profile
2 {
3 protected override void Configure()
4 {
5 CreateMap<User, UserDto>()
6 .ForMember(d => d.Name2, opt =>
7 {
8 opt.MapFrom(s => s.Name);
9 });
10 }
11 }

使用时就这样

 1     Mapper.Initialize(x => x.AddProfile<UserProfile>());
2
3 User user = new User()
4 {
5 Id = 1,
6 Name = "caoyc",
7 Age = 20
8 };
9
10 var dto = Mapper.Map<UserDto>(user);

四、空值替换NullSubstitute

空值替换允许我们将Source对象中的空值在转换为Destination的值的时候,使用指定的值来替换空值。

 1     public class UserProfile : Profile
2 {
3 protected override void Configure()
4 {
5 CreateMap<User, UserDto>()
6 .ForMember(d => d.Name2, opt => opt.MapFrom(s => s.Name))
7 .ForMember(d => d.Name2, opt => opt.NullSubstitute("值为空"));
8
9 }
10 }
1     Mapper.Initialize(x => x.AddProfile<UserProfile>());
2
3 User user = new User()
4 {
5 Id = 1,
6 Age = 20
7 };
8
9 var dto = Mapper.Map<UserDto>(user);

结果为:

五、忽略属性Ignore

 1     public class User
2 {
3 public int Id { get; set; }
4 public string Name { get; set; }
5 public int Age { get; set; }
6 }
7
8 public class UserDto
9 {
10 public string Name { get; set; }
11 public int Age { get; set; }
12
13 }
14
15 public class UserProfile : Profile
16 {
17 protected override void Configure()
18 {
19 CreateMap<User, UserDto>().ForMember("Name", opt => opt.Ignore());
20 }
21 }

使用

 1     Mapper.Initialize(x => x.AddProfile<UserProfile>());
2
3 User user = new User()
4 {
5 Id = 1,
6 Name="caoyc",
7 Age = 20
8 };
9
10 var dto = Mapper.Map<UserDto>(user);

结果:

六、预设值

如果目标属性多于源属性,可以进行预设值

 1     public class User
2 {
3 public int Id { get; set; }
4 public string Name { get; set; }
5 public int Age { get; set; }
6 }
7
8 public class UserDto
9 {
10 public string Name { get; set; }
11 public int Age { get; set; }
12 public string Gender { get; set; }
13
14 }
15
16 public class UserProfile : Profile
17 {
18 protected override void Configure()
19 {
20 CreateMap<User, UserDto>();
21 }
22 }

使用

 1     Mapper.Initialize(x => x.AddProfile<UserProfile>());
2
3 User user = new User()
4 {
5 Id = 1,
6 Name="caoyc",
7 Age = 20
8 };
9
10 UserDto dto = new UserDto() {Gender = "男"};
11 Mapper.Map(user, dto);

七、类型转换ITypeConverter

如果数据中Gender存储的int类型,而DTO中Gender是String类型

1     public class User
2 {
3 public int Gender { get; set; }
4 }
5
6 public class UserDto
7 {
8 public string Gender { get; set; }
9 }

类型转换类,需要实现接口ITypeConverter

 1     public class GenderTypeConvertert : ITypeConverter<int, string>
2 {
3 public string Convert(int source, string destination, ResolutionContext context)
4 {
5 switch (source)
6 {
7 case 0:
8 destination = "男";
9 break;
10 case 1:
11 destination = "女";
12 break;
13 default:
14 destination = "未知";
15 break;
16 }
17 return destination;
18 }
19 }

配置规则

 1     public class UserProfile : Profile
2 {
3 protected override void Configure()
4 {
5 CreateMap<User, UserDto>();
6
7 CreateMap<int, string>().ConvertUsing<GenderTypeConvertert>();
8 //也可以写这样
9 //CreateMap<int, string>().ConvertUsing(new GenderTypeConvertert());
10 }
11 }

使用

 1     Mapper.Initialize(x => x.AddProfile<UserProfile>());
2
3 User user0 = new User() { Gender = 0 };
4 User user1 = new User() { Gender = 1 };
5 User user2 = new User() { Gender = 2 };
6 var dto0= Mapper.Map<UserDto>(user0);
7 var dto1 = Mapper.Map<UserDto>(user1);
8 var dto2 = Mapper.Map<UserDto>(user2);
9
10 Console.WriteLine("dto0:{0}", dto0.Gender);
11 Console.WriteLine("dto1:{0}", dto1.Gender);
12 Console.WriteLine("dto2:{0}", dto2.Gender);

结果

八、条件约束Condition

当满足条件时才进行映射字段,例如人类年龄,假设我们现在人类年龄范围为0-200岁(这只是假设),只有满足在这个条件才进行映射

DTO和Entity

1     public class User
2 {
3 public int Age { get; set; }
4 }
5
6 public class UserDto
7 {
8 public int Age { get; set; }
9 }

Profile

1     public class UserProfile : Profile
2 {
3 protected override void Configure()
4 {
5 CreateMap<User, UserDto>().ForMember(dest=>dest.Age,opt=>opt.Condition(src=>src.Age>=0 && src.Age<=200));
6 }
7 }

使用代码

 1     Mapper.Initialize(x => x.AddProfile<UserProfile>());
2
3 User user0 = new User() { Age = 1 };
4 User user1 = new User() { Age = 150 };
5 User user2 = new User() { Age = 201 };
6 var dto0= Mapper.Map<UserDto>(user0);
7 var dto1 = Mapper.Map<UserDto>(user1);
8 var dto2 = Mapper.Map<UserDto>(user2);
9
10 Console.WriteLine("dto0:{0}", dto0.Age);
11 Console.WriteLine("dto1:{0}", dto1.Age);
12 Console.WriteLine("dto2:{0}", dto2.Age);

输出结果

转载 c# automapper 使用(一) https://www.cnblogs.com/caoyc/p/6367828.html的更多相关文章

  1. 转载 mvc:message-converters简单介绍 https://www.cnblogs.com/liaojie970/p/7736098.html

    mvc:message-converters简单介绍 说说@ResponseBody注解,很明显这个注解就是将方法的返回值作为reponse的body部分.我们进一步分析下这个过程涉及到的内容,首先就 ...

  2. Spring MVC 向页面传值-Map、Model和ModelMap https://www.cnblogs.com/caoyc/p/5635878.html

    Spring MVC 向页面传值-Map.Model和ModelMap 除了使用ModelAndView方式外.还可以使用Map.Model和ModelMap来向前台页面创造 使用后面3种方式,都是在 ...

  3. 【redis】redis五大类 用法 【转载:https://www.cnblogs.com/yanan7890/p/6617305.html】

    转载地址:https://www.cnblogs.com/yanan7890/p/6617305.html

  4. Bootstrap-table 使用总结 转载https://www.cnblogs.com/laowangc/p/8875526.html

    一.什么是Bootstrap-table? 在业务系统开发中,对表格记录的查询.分页.排序等处理是非常常见的,在Web开发中,可以采用很多功能强大的插件来满足要求,且能极大的提高开发效率,本随笔介绍这 ...

  5. 使用java实现单链表(转载自:https://www.cnblogs.com/zhongyimeng/p/9945332.html)

    使用java实现单链表----(java中的引用就是指针)转载自:https://www.cnblogs.com/zhongyimeng/p/9945332.html ? 1 2 3 4 5 6 7 ...

  6. Autofac框架详解 转载https://www.cnblogs.com/lenmom/p/9081658.html

    一.组件 创建出来的对象需要从组件中来获取,组件的创建有如下4种(延续第一篇的Demo,仅仅变动所贴出的代码)方式: 1.类型创建RegisterType AutoFac能够通过反射检查一个类型,选择 ...

  7. 关于pipeline的一篇转载博文https://www.cnblogs.com/midhillzhou/p/5588958.html

    引用自https://www.cnblogs.com/midhillzhou/p/5588958.html 1.pipeline的产生 从一个现象说起,有一家咖啡吧生意特别好,每天来的客人络绎不绝,客 ...

  8. 转载 https://www.cnblogs.com/bobo-pcb/p/11708459.html

    https://www.cnblogs.com/bobo-pcb/p/11708459.html #### 1 用VMware 15.0+win10企业版 1次安装成功 20200124 2 不要用v ...

  9. 干货,不小心执行了rm -f,除了跑路,如何恢复?https://www.cnblogs.com/justmine/p/10359186.html

    前言 每当我们在生产环境服务器上执行rm命令时,总是提心吊胆的,因为一不小心执行了误删,然后就要准备跑路了,毕竟人不是机器,更何况机器也有bug,呵呵. 那么如果真的删除了不该删除的文件,比如数据库. ...

随机推荐

  1. NABCD校园生活

    N(Need,需求) 在校师生得到的信息分散,极大的影响了师生的学习效率,所以就会有快速得到全面信息的需求,而我们的APP正是在解决这个问题. A(Approach,做法) 我们会在主页进行信息分类, ...

  2. 因 URL 意外地以“/HelloWorld”结束,请求格式无法识别。

    WebService中发布之后出现这个错误, 解决方法: web.config文件中的 <system.web> 节点下加入:<webServices>    <prot ...

  3. [PHP] 算法-数组归并排序并计算逆序对的个数的PHP实现

    在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对.输入一个数组,求出这个数组中的逆序对的总数P.并将P对1000000007取模的结果输出. 即输出P%100000000 ...

  4. [android] 手机卫士读取联系人

    获取ContentResolver内容解析器对象,通过getContentResolver()方法 调用ContentResolver对象的query()方法,得到raw_contacts表里面的数据 ...

  5. 【18】观察者模式(Observer Pattern)

    一.引言 在现实生活中,处处可见观察者模式.例如,微信中的订阅号,订阅博客和QQ微博中关注好友,这些都属于观察者模式的应用.在这一章将分享我对观察者模式的理解,废话不多说了,直接进入今天的主题. 二. ...

  6. 初学HTML-10

    marquee标签:设置文字滚动效果. 格式:<marquee>文字滚动</marquee> 属性:direction:设置滚动方向:left / right / up / d ...

  7. vue路由传参的三种基本方式

    现有如下场景,点击父组件的li元素跳转到子组件中,并携带参数,便于子组件获取数据. 父组件中: <li v-for="article in articles" @click= ...

  8. table垂直居中

    th,td{ text-align:center;/** 设置水平方向居中 */ vertical-align:middle/** 设置垂直方向居中 */ }

  9. hosts 文件

    各系统平台hosts文件存放路径 路径如下: Windows系统: C:\Windows\System32\drivers\etc\hosts        Linux系统:/etc/hosts    ...

  10. Windows 10修复

    [以管理员运行如下命令]: 1.sfc /scannow 命令将扫描所有受保护的系统文件,并用位于 %WinDir%\System32\dllcache 的压缩文件夹中的缓存副本替换损坏的文件. 2. ...