Introduction and use of AutoMapper (1), automapper Introduction
Software Environment
- Vs2015
- Asp.net mvc 5
- . NET Framework 4.5.2
- AutoMapper 5.2.0.0
AutoMapper Installation
Create an asp.net mvc project AutoMapperExample. Here we should use vs to create an mvc project.
,
Click Tools → NuGetB Package Manager → manage the NuGet package of the solution. On the displayed page, select Browse, enter autoMapper, and press enter to search. In the searched package, select the first one, and then install
As shown in, AutoMapper is successfully installed.
AutoMapper Configuration
If you use static Global er registration, it should be placed at the application startup, that is, the Application_Start () method of the Global. asax file of ASP. net mvc.
Create an AutoMapper folder in the program to store the class of object ing. in this folder, create AutoMapperConfig, which processes all object ing.
This class mainly processes object ing, that is, converting from one object to another
public class AutoMapperConfig { public static void Config() { Mapper.Initialize(cfg => { cfg.CreateMap<OrderDto, Order>(); cfg.AddProfile<ExtendMapProfile>(); }); } public class ExtendMapProfile : Profile { protected override void Configure() { CreateMap<UserDto, User>(); } } }
Here, Order, OrderDto, User, and UserDto are Entity objects, which are not described in detail. CreateMap <> converts two objects to AutoMapper, which will be described in detail later. When a new object is added for conversion, createMag <source, dest> conversion is performed here.
Execute this static method in the Application_Start () method of the Global. asax file.
protected void Application_Start() { AutoMapperConfig.Config(); AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); }
So far, all AutoMapper configurations have been completed.