c# automapper 使用(一)

來源:互聯網
上載者:User

標籤:大小   簡單   rom   image   ddp   span   ber   err   屬性   

一、最簡單的用法

有兩個類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 = 207     };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 = 2013     };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 使用(一)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.