c# automapper 使用(一)

摘要:
1、 最简单的用法有两个类:User和UserDtopublicclassUser2{3PublicintId{get;set;}4publicstringName{get;set;}5PublicentAge{get;set;}6} 78publicclassUserDto9{10publicstringName{get;set;}11publicintAge{get;set;}12} 转换用户

一、最简单的用法

有两个类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);

c# automapper 使用(一)第1张

三、使用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);

结果为:

c# automapper 使用(一)第2张

五、忽略属性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);

结果:

c# automapper 使用(一)第3张

六、预设值

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

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

c# automapper 使用(一)第4张

 七、类型转换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);

结果

c# automapper 使用(一)第5张

八、条件约束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 使用(一)第6张

免责声明:文章转载自《c# automapper 使用(一)》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇vue项目安装vconsole的时候出现的bug在TOMCAT下配置工程的默认访问设置(转)下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

在javaweb的项目当中实现随机数字的生成

首先,需要在javaweb的项目当中新建一个Servlet文件,然后再web.xml中配置一下: 这样运行的时候就可以通过“http://localhost:8080/Response/Response02”的地址访问到我们的Servlet。 开始代码的编写吧: 首先,我们需要写一个生成随即数字的方法,我们这次实现随即生成七位数的数字: priv...

java的输入输出

0x01:输出流 java常用的输出语句有下面三种: System.out.println();//换行打印,输出之后会自动换行  System.out.print();//不换行打印 System.out.printf();//按格式输出 0x02:输出示例 public class test { public static void...

java 实现基于opencv全景图合成

因项目需要,自己做了demo,从中学习很多,所以分享出来,希望有这方面需求的少走一些弯路,opencv怎么安装网上教程多多,这里不加详细说明,我安装的opencv-3.3.0  如上图所示,找到相应的jar包,这里讲一下如何这个jar如何导入Maven仓库 mvn install:install-file -Dfile=D:opencv-3.0.0ope...

Spring 框架的事务管理

1. Spring 框架的事务管理相关的类和API PlateformTransactionManager 接口: 平台事务管理器(真正管理事务的类); TransactionDefinition 接口: 事务定义信息(事务的隔离级别,传播行为,超时,只读等); TransactionStatus 接口: 事务的状态; 平台事务管理器真正管理事务对...

Java二维码的制作

二维码现在已经到处都是了,下面是二维码的介绍 :二维码 ,又称 二维条码 , 二维条形码最早发明于日本,它是用某种特定的几何图形按一定规律在平面(二维方向上)分布的黑白相间的图形记录数据符号信息的,在代码编制上巧妙地利用构 成计算机内部逻辑基础的“0”、“1”比特流的概念,使用若干个与二进制相对应的几何形体来表示文字数值信息,通过图象输入设备或光电扫描设备...

iOS Document Interaction(预览和打开文档) 编程指南

原文:http://developer.apple.com/library/ios/#documentation/FileManagement/Conceptual/DocumentInteraction_TopicsForIOS/Introduction/Introduction.html   关于 DocumentInteraction   iOS支持...