C # AutoMapper use (i)

Source: Internet
Author: User

One, the simplest usage

There are two classes of user and Userdto

1      Public classUser2     {3          Public intId {Get;Set; }4          Public stringName {Get;Set; }5          Public intAge {Get;Set; }6     }7 8      Public classUserdto9     {Ten          Public stringName {Get;Set; } One          Public intAge {Get;Set; } A}

Converting user to Userdto is also simple

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

This is one of the simplest to use, AutoMapper will be more field names go automatically for, ignoring case.

Second, if the property name is different

Change the Name property of Userdto to Name2

1Mapper.initialize (x =2X.createmap<user, userdto>()3. Formember (d =>d.name2, opt = = {4Opt. Mapfrom (s = =s.name);5             })6         );7 8User User =NewUser ()9     {TenId =1, OneName ="Caoyc", AAge = - -     }; -  the     varDTO = mapper.map<userdto> (user);

Third, using profile configuration

Customize a UserProfile class to inherit the profile and override the Configure method

1      Public classUserprofile:profile2     {3         protected Override voidConfigure ()4         {5Createmap<user, userdto>()6. Formember (d = d.name2, opt = =7                 {8Opt. Mapfrom (s = =s.name);9                 });Ten         } One}

That's it when you use it

1Mapper.initialize (x = x.addprofile<userprofile>());2 3User User =NewUser ()4     {5Id =1,6Name ="Caoyc",7Age = -8     };9 Ten     varDTO = mapper.map<userdto> (user);

C # AutoMapper use (i)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.