AutoMapper is used for object mapping in ASP.NET Core Web
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!
- ASP.NET Core uses cookies in WebApi projects
- ASP.NET Core invokes WebService using HttpClient
- Methods that call WebService in an ASP.NET Core project
- Create an ASP.NET Core Web application and introduce project templates
- The Core namespace ASP.NET System. Text. Encodings. Web is introduced
- asp.net core webapi file upload function implementation
- Method steps for deploying the ASP.NET Core Web API on IIS
- ASP.NET Core implements custom WebApi model validation details
Related article
-
.NET 6 developers of TodoList applications use AutoMapper to implement GET requests
The requests we want to accept and the values we return have two principles: Each model is consumed by one and only one API; Each model contains only the necessary fields or attributes that the API sponsor wants to include. The AutoMapper library exists to fulfill this requirement. This article will introduce how AutoMapper implements GET requests, you can refer to it2021-12-12 -
.NET oscilloscope control example code analysis
This article is a detailed analysis of.NET oscilloscope controls, the need for a friend's reference2013-05-05 -
An example of asp.net implementing a three-tier architecture
This article mainly introduces the asp.net implementation of three-layer architecture examples, very simple and practical, there is a need for small partners can refer to the next.2015-07-07 -
ASP.NET wechat public number user group management web page
This article mainly introduces in detail the user group management web page of ASP.NET wechat public number, which has certain reference value, interested partners can refer to it2016-11-11 -
asp page and Asp.net page transmission Chinese parameter UrlEncode encoding and receiving decoding
Put a link in asp to point to the asp.net web page, but the asp.net Web address is converted by HttpUtility.UrlEncode and decoded by HttpUtility.UrlDecode. While asp server.urlencode and HttpUtility.UrlEncode encoding is different.2010-04-04 -
ASP.NET Control Development series for picture switching web controls
Just began to learn control development, wrote a web picture switching control, welcome to shoot bricks.2010-04-04 -
Asp.net handles the problem of sharing sessions between different Web applications on a site
Asp.net handles the problem of sharing sessions between different Web applications on a site...2006-09-09 -
The Access connection for ASP.NET database programming failed
Access connection failed for ASP.NET database programming...2006-09-09 -
asp.net FreeTextBox configuration details
FreeTextBox is an open source server control. We can easily embed it in Web Forms to enable online editing of HTML content.2009-11-11
Latest comments