Object Mapping with AutoMapper in ASP.NET Core Web _ Practical Tips _ Home of Scripts

AutoMapper is used for object mapping in ASP.NET Core Web

Updated: May 17, 2024 15:12:12 By: Time Chasers
AutoMapper is a simple to use. NET object mapping library, for quick and easy conversion and mapping between objects, greatly simplifying the workload of developers in dealing with object mapping, today we talk about the use of AutoMapper in ASP.NET Core Web for quick object mapping, interested friends follow Xiaobian together to see it

introduction

In daily development, we often need to map one object to another object, and this process may need to write a lot of repetitive code, if you write it manually every time, not only will affect the development efficiency, but also prone to errors when the project is more and more complex and large. In order to solve this problem, the object mapping library comes out, these libraries can automatically complete the mapping between objects, thus reducing a lot of development workload, improve the development efficiency. Today we're going to talk about using AutoMapper for fast object mapping in ASP.NET Core Web.

What are the benefits of using the object mapping library?

  • Reduce development workload and improve development efficiency.
  • Reduce errors and bugs in the development process.
  • Simplify code structure, improve code readability and maintainability.

Introduction to AutoMapper object mapping library

AutoMapper is a simple to use. NET object mapping library, used to quickly and easily convert and map between objects, greatly simplifying the workload of developers when dealing with object mapping.

  • Making open source address: https://github.com/AutoMapper/AutoMapper
  • Online document address: https://docs.automapper.org/en/stable/Getting-started.html

Install the AutoMapper NuGet package

Search in the ASP.NET Core Web API project: AutoMapper NuGet package installation.

Create source and target objects

Next we define a source object (Student) and a target object (StudentViewModel).

Student (source object)

public class Student {/// <summary> /// Student ID [primary key, AutoIncrement] /// </summary> [PrimaryKey, AutoIncrement] [Display(Name = "student ID")] public int StudentID {get; set; } /// <summary> /// class ID /// </summary> [Display(Name = "class ID")] public int ClassID {get; set; } /// <summary> /// Student Name /// </summary> [Display(Name = "student name ")] public string Name {get; set; } /// <summary> /// student Age /// </summary> [Display(Name = "student age ")] public int Age {get; set; } /// <summary> /// student Gender /// </summary> [Display(Name = "student gender ")] public string Gender {get; set; }}

StudentViewModel (target object)

public class StudentViewModel {/// <summary> /// Student ID [primary key, AutoIncrement] /// </summary> [PrimaryKey, AutoIncrement] [Display(Name = "student ID")] public int StudentID {get; set; } /// <summary> /// class ID /// </summary> [Display(Name = "class ID")] public int ClassID {get; set; } /// <summary> /// Student Name /// </summary> [Display(Name = "student name ")] public string Name {get; set; } /// <summary> /// student Age /// </summary> [Display(Name = "student age ")] public int Age {get; set; } /// <summary> /// student Gender /// </summary> [Display(Name = "student gender ")] public string Gender {get; set; } /// <summary> /// class Name /// </summary> [Display(Name = "class name ")] public string ClassName {get; set; }}

Configure the AutoMapper mapping rule

We can define an AutoMapperMappingProfile mapping profile in which we define the mapping between source and target types.

using AutoMapper; using Entity; using Entity.ViewModel; namespace WebApi {/// <summary> /// AutoMapper mapping configuration file /// </summary> public class AutoMapperMappingProfile: Profile {/// <summary> /// Add a mapping rule /// / </summary> public AutoMapperMappingProfile() {CreateMap<Student, StudentViewModel>(); }}}

Program to register the AutoMapper service

Using the AddAutoMapper() method, you can add the services required by AutoMapper to this collection for use in other parts of your application. This method requires passing in an Assembly array to tell AutoMapper which assemblies to scan for mapping configurations (scanning AutoMapper's configuration files in all assemblies in the current scope).

public static void Main(string[] args) { var builder = WebApplication.CreateBuilder(args); builder.Services.AddControllers(); // AddAutoMapper configuration // Use the AddAutoMapper() method to add the services required by AutoMapper to this collection for use in other parts of the application. // This method needs to pass in an Assembly array to tell AutoMapper which assemblies to scan for mapping configurations (scans AutoMapper's configuration files in all assemblies in the current scope). builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); }

Perform object mapping operations

Dependency injection gets an instance of the IMapper interface

/// <summary> /// Student management /// </summary> [ApiController] [Route("api/[controller]/[action]")] public class StudentController : ControllerBase { private readonly IMapper _mapper; /// <summary> /// Dependency injection /// </summary> /// <param name="mapper">mapper</param> public StudentController(IMapper mapper) {  _mapper = mapper; }}

Perform object mapping operations

Next we use the Map method using the IMapper interface to map objects.

var studentsListDto = _mapper.Map<List<StudentViewModel>>(students);

Mapping result output

Complete sample source code

DotNetGuide Technical community communication group

  • DotNetGuide Technology community is a oriented. NET developers open source technology community, designed to provide developers with a comprehensive C#/.NET/.NET core-related learning materials, technical sharing and consulting, project framework recommendations, job search and recruitment information, and problem solving platform.
  • In the DotNetGuide technical community, developers can share their technical articles, project experiences, learning experiences, difficult technical problems and solutions, and have the opportunity to meet like-minded developers.
  • We are committed to building a positive, harmonious and friendly society. NET technology exchange platform. Whether you are a beginner or an experienced developer, we want to provide you with more value and growth opportunities.

This article about the use of AutoMapper for object mapping in ASP.NET Core Web is introduced to this, more related ASP.NET Core Web object mapping content please search the previous articles of Script Home or continue to browse the following related articles hope that you will support Script home in the future!

Related article

Latest comments