转载 c# automapper 使用(一) https://www.cnblogs.com/caoyc/p/6367828.html
一、最简单的用法
有两个类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的更多相关文章
- 转载 mvc:message-converters简单介绍 https://www.cnblogs.com/liaojie970/p/7736098.html
mvc:message-converters简单介绍 说说@ResponseBody注解,很明显这个注解就是将方法的返回值作为reponse的body部分.我们进一步分析下这个过程涉及到的内容,首先就 ...
- Spring MVC 向页面传值-Map、Model和ModelMap https://www.cnblogs.com/caoyc/p/5635878.html
Spring MVC 向页面传值-Map.Model和ModelMap 除了使用ModelAndView方式外.还可以使用Map.Model和ModelMap来向前台页面创造 使用后面3种方式,都是在 ...
- 【redis】redis五大类 用法 【转载:https://www.cnblogs.com/yanan7890/p/6617305.html】
转载地址:https://www.cnblogs.com/yanan7890/p/6617305.html
- Bootstrap-table 使用总结 转载https://www.cnblogs.com/laowangc/p/8875526.html
一.什么是Bootstrap-table? 在业务系统开发中,对表格记录的查询.分页.排序等处理是非常常见的,在Web开发中,可以采用很多功能强大的插件来满足要求,且能极大的提高开发效率,本随笔介绍这 ...
- 使用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 ...
- Autofac框架详解 转载https://www.cnblogs.com/lenmom/p/9081658.html
一.组件 创建出来的对象需要从组件中来获取,组件的创建有如下4种(延续第一篇的Demo,仅仅变动所贴出的代码)方式: 1.类型创建RegisterType AutoFac能够通过反射检查一个类型,选择 ...
- 关于pipeline的一篇转载博文https://www.cnblogs.com/midhillzhou/p/5588958.html
引用自https://www.cnblogs.com/midhillzhou/p/5588958.html 1.pipeline的产生 从一个现象说起,有一家咖啡吧生意特别好,每天来的客人络绎不绝,客 ...
- 转载 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 ...
- 干货,不小心执行了rm -f,除了跑路,如何恢复?https://www.cnblogs.com/justmine/p/10359186.html
前言 每当我们在生产环境服务器上执行rm命令时,总是提心吊胆的,因为一不小心执行了误删,然后就要准备跑路了,毕竟人不是机器,更何况机器也有bug,呵呵. 那么如果真的删除了不该删除的文件,比如数据库. ...
随机推荐
- VirtualBox安装CentOS7
一:.下载CentOS7的镜像 下载地址:https://www.centos.org/download/ 进入后有三个版本可以选择: 1.DVD ISO 标准安装版,一般下载这个就可以了(推荐)本 ...
- mysql实践总结
首先介绍mysql的安装和基本使用.进阶操作.讲解mysql的导入导出和自动备份,然后介绍安全模式修改密码和mysql的全文本搜索功能,最后记录了个人使用mysql中遇到的问题集,闲暇时我也会多看几次 ...
- Java 雇员管理小练习(理解面向对象编程)
在学习集合框架的时候,初学者很容易练习到学生管理系统.雇员管理体统等练习题.在学习集合框架之前,基本上Java基本语法都学完了,集合框架也从侧面的检验对前面学习的理解.下面用一个曾经做过的练习题,回顾 ...
- Android系统常用URI
android系统常用URI android系统管理联系人的URI如下: ContactsContract.Contacts.CONTENT_URI 管理联系人的Uri ContactsContrac ...
- csharp:SMO run sql script
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; usin ...
- 警告!中国90%AI初创企业将在两年内落败出局
https://mp.weixin.qq.com/s/-RkyLda1jovaHBlBTsi-BA 近年来,中国涌现了一大批AI初创企业,但AI热潮也伴随着泡沫.由于近期市场资金紧缩,投资者发出警告, ...
- Android studio 在一个项目上添加另一个项目,引用其内部参数
Setting.gradle 里面 添加 include ':app',‘imagePicker’ 其中 imagePicker 为要引入的项目名 build.gradle(Module: app) ...
- recovery 升级过程LED灯闪烁
Android设备在进入recovery升级的过程,我们在屏幕上面可以看到升级的机器人动画,以及升级的进度显示.这仅限于有屏幕的设备,比如平板PAD,电视TV等,对与没有屏幕的盒子BOX,那么在不接入 ...
- TensorFlow实现梯度下降
# -*- coding: utf-8 -*- """ Created on Mon Oct 15 17:38:39 2018 @author: zhen "& ...
- Python中DataFrame关联
df = pd.merge( df, # 左 wzplbm, # 右 left_on = ['WZBM','ZBWZMC'], # 左DataFrame匹配列 right_on = ['WZPLBM' ...