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)