AutoMapper Object Mapping Tool: The main point is to turn one entity into another.
1. Refer to NuGet packages; Search: AutoMapper
2. Create an entity class
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespaceautomapper{ Public Static classautomapperextension {/// <summary> ///Single Object Mapping/// </summary> /// <typeparam name= "TSource" >Source Object</typeparam> /// <typeparam name= "Tdestination" >target Object</typeparam> /// <param name= "source" ></param> /// <returns></returns> Public StaticTdestination Mapto<tsource, tdestination>(TSource source) {if(Source = =NULL)return default(tdestination); Mapper.initialize (x= X.createmap (typeof(TSource),typeof(tdestination))); returnMapper.map<tdestination>(source); } /// <summary> ///Collection List Type mappings/// </summary> /// <typeparam name= "TSource" >Source Object</typeparam> /// <typeparam name= "Tdestination" >target Object</typeparam> /// <param name= "source" ></param> /// <returns></returns> Public StaticList<tdestination> Maptolist<tsource, Tdestination> ( ThisIenumerable<tsource>source) { if(Source = =NULL)return default(list<tdestination>); Mapper.initialize (x= X.createmap (typeof(TSource),typeof(tdestination))); returnMapper.map<list<tdestination>>(source); } }}
3. As an example. Create two Entity objects
(Old member entity)
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespaceautomapper{ Public classUsermodel {/// <summary> ///member Number/// </summary> PublicInt32 UserId {Get;Set; } /// <summary> ///member name/// </summary> PublicString Name {Get;Set; } }}
New Member Entity
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespaceautomapper{/// <summary> ///New Membership Form/// </summary> Public classUsernewmodel {/// <summary> ///member Number/// </summary> PublicInt32 UserId {Get;Set; } /// <summary> ///member name/// </summary> PublicString Name {Get;Set; } }}
4. How to use it. In the process of the project. If you need to convert two of entities. Working with instances
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespaceautomapper{ Public classExtension {/// <summary> ///turn user into usernew/// </summary> Public Static voidModel () {varuser =NewUsermodel () {UserId=1, Name="Wang Bin" }; varUsernew =NewUsernewmodel (); //transfer old member entity to new member entity varU = automapperextension.mapto<usermodel,usernewmodel>(user); } Public Static voidmodellist () {List<UserModel> Users =NewList<usermodel>(); varuser =NewUsermodel () {UserId=1, Name="Wang Bin" }; Users.add (user); varUsernew =NewList<usernewmodel>(); //transfer old member entity to new member entity varUlist = Automapperextension.maptolist<usermodel, usernewmodel>(Users); } }}
. NET AutoMapper Object Mapping tool application