Method of Object Mapping Using AutoMapper in. NET CORE

Time:2019-8-13

brief introduction

AutoMapper uses a fluent configuration API to define an object-object mapping strategy. AutoMapper uses a convention-based matching algorithm to match up source to destination values. AutoMapper is geared towards model projection scenarios to flatten complex object models to DTOs and other simple objects, whose design is better suited for serialization, communication, messaging, or simply an anti-corruption layer between the domain and application layer.

Official website: http://automapper.org/

Document: https://automapper.readthedocs.io/en/latest/index.html

GitHub:https://github.com/AutoMapper/AutoMapper/blob/master/docs/index.rst

Platform support:

  • .NET 4.6.1+
  • .NET Standard 2.0+ https://docs.microsoft.com/en-us/dotnet/standard/net-standard

Use

Nuget installation

AutoMapper  
AutoMapper. Extensions. Microsoft. Dependency Injection // Dependency Injection into AutoMapper requires downloading the package.

Add AutoMapper to Startup

public void ConfigureServices(IServiceCollection services)
{
 services.AddMvc();
 // Add support for AutoMapper
 services.AddAutoMapper();
}

Create AutoMapper mapping rules

public class AutoMapperConfigs:Profile
{
 // Add your entity mapping relationship.
 public AutoMapperConfigs()
 {
  CreateMap<DBPoundSheet, PoundSheetViewModel>();
  CreateMap<PoundSheetViewModel, DBPoundSheet>();
 }
}

Insert your IMapper into the constructor


IMapper _mapper;

public PoundListController(IMapper mapper)
{
 _mapper = mapper;
}

Single Object Conversion


//typeof(model)="PoundSheetViewModel"
DBPoundSheet dBPoundSheet = _mapper.Map<DBPoundSheet>(model);

Conversion of Collective Objects

summary

Above is the whole content of this article. I hope the content of this article has some reference value for your study or work. Thank you for your support to developpaer.

Recommended Today

Server Core Knowledge

Catalog 1. Computer: a tool to assist human brain 2. Composition of computer hardware 3. power supply 4.CPU 5. memory 6. Classification of computer use 7. Introduction to common Internet servers 8. Server classification 1. Computer: a tool to assist human brain Nowadays people touch computers almost all the time! Whether it’s a desktop computer, […]