首页 > 代码库 > c# automapper 使用(一)

c# automapper 使用(一)

一、最简单的用法

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

 

c# automapper 使用(一)