Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to implement entity Mapping with AutoMapper in ASP.NET Core

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article will explain in detail how ASP.NET Core uses AutoMapper to achieve entity mapping. The editor thinks it is very practical, so I share it for you as a reference. I hope you can get something after reading this article.

I. Preface

In the actual project development process, we use a variety of ORM frameworks to enable us to quickly obtain the data, and can bind the obtained data to the corresponding List, and then the page or interface directly displays the data in the List. But in the end, there may be differences between the data and database entities that we want to display in the view or interface, and the general approach is to create some corresponding "model" classes, and then process the acquired data again to meet the needs.

Therefore, if it is convenient to implement the entity mapping between database persistence objects and model objects, and avoid implementing this process manually in de-code, the workload of development can be greatly reduced. AutoMapper is a tool that can help us implement the entity transformation process.

Second, use AutoMapper to realize entity mapping

AutoMapper is an OOM (Object-Object-Mapping) component, as can be seen from its English name, AutoMapper is mainly to achieve the conversion between entities, so as to avoid us to convert manually every time. Before there is no component such as OOM, if we need to achieve the transformation between entities, we can only use manual modification of the code, and then assign values one by one to achieve the mapping, and with the OOM component, we can easily help us to achieve this requirement. Look at the following example.

First create an ASP.NET Core WebApi project:

Add a Student entity class:

Namespace AutoMapperDemo.Model {public class Student {public int ID {get; set;} public string Name {get; set;} public int Age {get; set;} public string Gender {get; set;}

Add the StudentDTO class, which is consistent with the Student property.

Then add a class to simulate some test data:

Using AutoMapperDemo.Model;using System.Collections.Generic;namespace AutoMapperDemo {public class Data {public static List ListStudent {get; set;} public static List GetList () {ListStudent = new List (); for (int I = 0; I

< 3; i++) { Student student = new Student() { ID=i, Name=$"测试_{i}", Age=20, Gender="男" }; ListStudent.Add(student); } return ListStudent; } }} 添加Student控制器,通过Get方法获取所有的值: using System.Collections.Generic;using System.Threading.Tasks;using AutoMapperDemo.Model;using Microsoft.AspNetCore.Mvc;namespace AutoMapperDemo.Controllers{ [Route("api/[controller]")] [ApiController] public class StudentController : ControllerBase { [HttpGet] public async Task Get() { List list = new List(); list = await Task.Run(() =>

{return Data.GetList ();}); return list;}

Test with Postman:

The returned data is directly the entity class type corresponding to the database. When the requirements change, we need to return data of type StudentDTO, and we need to modify the code:

Using System.Collections.Generic;using System.Threading.Tasks;using AutoMapperDemo.DTO;using AutoMapperDemo.Model;using Microsoft.AspNetCore.Mvc;namespace AutoMapperDemo.Controllers {[Route ("api/ [controller]")] [ApiController] public class StudentController: ControllerBase {[HttpGet] public async Task Get () {List list = new List () List = await Task.Run (() = > {return Data.GetList ();}); return list;} [HttpGet ("GetDTO")] public async Task GetDto () {List list = new List () List listStudent = await Task.Run (() = > {return Data.GetList ();}); / / Loop assign foreach (var item in listStudent) {StudentDTO dto = new StudentDTO (); dto.ID = item.ID; dto.Name = item.Name Dto.Age = item.Age; dto.Gender = item.Gender; / / add list.Add (dto) to the collection;} return list;}}

Or use Postman for testing:

You can see that data of type DTO is returned at this time. In this case, as we said above, you need to manually modify the code, and then loop to assign values to the corresponding properties. Here the Student class has only four attributes, and if there are a lot of attributes, or if they are used in many places, it will be troublesome to assign values in this way. If one of the attribute names changes in the future, then all places need to be modified, and the workload will be heavy. At this point you need to use AutoMapper to solve the problem.

First, the AutoMapper package is introduced, which is directly introduced into NuGet:

Choose to install the AutoMapper.Extensions.Microsoft.DependencyInjection package here. The main purpose of this package is to allow us to use AutoMapper through dependency injection.

Create a new StudentProfile class, which inherits from AutoMapper's Profile class. In the no-parameter constructor, we can use the CreateMap method to create a mapping between two entities.

Using AutoMapper;using AutoMapperDemo.DTO;using AutoMapperDemo.Model Namespace AutoMapperDemo.AutoMapper {/ inherits from the Profile class / public class StudentProfile: Profile {/ the constructor implements mapping / public StudentProfile () {/ / Mapping / / the first argument is the source type (here is the Model type) The second parameter is the target type (in this case, the DTO type) CreateMap () }}}

What is the use of Profile here? Services.AddAutoMapper he will automatically find all classes that inherit Profile and configure them.

Then modify the Student controller, use the injection of AutoMapper through the constructor, and use AutoMapper for automatic mapping:

Using System.Collections.Generic;using System.Threading.Tasks;using AutoMapper;using AutoMapperDemo.DTO;using AutoMapperDemo.Model;using Microsoft.AspNetCore.Mvc;namespace AutoMapperDemo.Controllers {[Route ("api/ [controller]")] [ApiController] public class StudentController: ControllerBase {private readonly IMapper _ mapper / public StudentController (IMapper mapper) {_ mapper = mapper;} [HttpGet] public async Task Get () {List list = new List () through constructor implementation List = await Task.Run (() = > {return Data.GetList ();}); return list;} [HttpGet ("GetDTO")] public async Task GetDto () {List list = new List () List listStudent = await Task.Run (() = > {return Data.GetList ();}); / Loop assigns values to attributes / / foreach (var item in listStudent) / / {/ / StudentDTO dto = new StudentDTO (); / / dto.ID = item.ID / / dto.Name = item.Name; / / dto.Age = item.Age; / / dto.Gender = item.Gender; / add to the collection / / list.Add (dto); / /} / / use AutoMapper to map list = _ mapper.Map (listStudent) Return list;}

Modify the ConfigureServices method of the Startup class to add AutoMapper:

Public void ConfigureServices (IServiceCollection services) {# region uses arrays of type AutoMapper / / parameters of type Assembly to indicate that AutoMapper will traverse these assembly arrays to find all configuration files that inherit the Profile class / / scan AutoMapper's configuration file services.AddAutoMapper (AppDomain.CurrentDomain.GetAssemblies ()) in all assemblies in the current scope; # endregion services.AddControllers ();}

Use Postman to test again:

As you can see, this also implements our requirements, and there is no need for manual mapping.

In the above example, the property names in the Student and StudentDTO classes are the same. What if the attribute names are different? We change the ID in the StudentDTO class to StudentID, and then modify the mapping code:

Using AutoMapper;using AutoMapperDemo.DTO;using AutoMapperDemo.Model Namespace AutoMapperDemo.AutoMapper {/ inherits from the Profile class / public class StudentProfile: Profile {/ the constructor implements mapping / public StudentProfile () {/ / Mapping / / the first argument is the source type (here is the Model type) The second parameter is the target type (in this case, the DTO type) / / CreateMap () / use custom mapping ID of Student class to StudentID CreateMap () .ForMember of StudentDTO class (destinationMember: des = > des.StudentID, memberOptions: opt = > {opt.MapFrom (mapExpression: map = > map.ID);});}

Use Postman to test again:

This implements the custom mapping. Here is a mapping of a field, what if multiple fields are different? Modify the StudentDTO class:

Namespace AutoMapperDemo.DTO {public class StudentDTO {public int StudentID {get; set;} public string StudentName {get; set;} public int StudentAge {get; set;} public string StudentGender {get; set;}

Then modify the mapping configuration class:

Using AutoMapper;using AutoMapperDemo.DTO;using AutoMapperDemo.Model Namespace AutoMapperDemo.AutoMapper {/ inherits from the Profile class / public class StudentProfile: Profile {/ the constructor implements mapping / public StudentProfile () {/ / Mapping / / the first argument is the source type (here is the Model type) The second parameter is the target type (in this case, the DTO type) / / CreateMap () / / use custom mapping ID of Student class to StudentID / / CreateMap () / .ForMember of StudentDTO class (destinationMember: des = > des.StudentID, memberOptions: opt = > {opt.MapFrom (mapExpression: map = > map.ID);}) / A custom mapping of multiple attributes CreateMap () .ForMember (destinationMember: des = > des.StudentID, memberOptions: opt = > {opt.MapFrom (mapExpression: map = > map.ID);}) .ForMember (destinationMember: des = > des.StudentName, memberOptions: opt = > {opt.MapFrom (mapExpression: map = > map.Name) ) .ForMember (destinationMember: des = > des.StudentAge, memberOptions: opt = > {opt.MapFrom (mapExpression: map = > map.Age);}) .ForMember (destinationMember: des = > des.StudentGender, memberOptions: opt = > {opt.MapFrom (mapExpression: map = > map.Gender);});}

Testing with Postman:

This enables custom mapping of multiple attributes.

In the above example, you map from Student to StudentDTO, so can you map from StudentDTO to Student? The answer is yes, just use the ReverseMap () method at the end of the mapping:

Using AutoMapper;using AutoMapperDemo.DTO;using AutoMapperDemo.Model Namespace AutoMapperDemo.AutoMapper {/ inherits from the Profile class / public class StudentProfile: Profile {/ the constructor implements mapping / public StudentProfile () {/ / Mapping / / the first argument is the source type (here is the Model type) The second parameter is the target type (in this case, the DTO type) / / CreateMap () / / use custom mapping ID of Student class to StudentID / / CreateMap () / .ForMember of StudentDTO class (destinationMember: des = > des.StudentID, memberOptions: opt = > {opt.MapFrom (mapExpression: map = > map.ID);}) / A custom mapping of multiple attributes CreateMap () .ForMember (destinationMember: des = > des.StudentID, memberOptions: opt = > {opt.MapFrom (mapExpression: map = > map.ID);}) .ForMember (destinationMember: des = > des.StudentName, memberOptions: opt = > {opt.MapFrom (mapExpression: map = > map.Name) ) .ForMember (destinationMember: des = > des.StudentAge, memberOptions: opt = > {opt.MapFrom (mapExpression: map = > map.Age);}) .ForMember (destinationMember: des = > des.StudentGender, memberOptions: opt = > {opt.MapFrom (mapExpression: map = > map.Gender);}) / / ReverseMap indicates bidirectional mapping. ReverseMap ();}

We modify Data by adding an Add method to add Student to the collection:

Using AutoMapperDemo.Model;using System.Collections.Generic;namespace AutoMapperDemo {public class Data {public static List ListStudent {get; set;} static Data () {ListStudent = new List (); for (int I = 0; I

< 3; i++) { Student student = new Student() { ID = i, Name = $"测试_{i}", Age = 20, Gender = "男" }; ListStudent.Add(student); } } public static List GetList() { return ListStudent; } public static void Add(Student entity) { ListStudent.Add(entity); } }} 修改Student控制器,添加一个Post方法,传入的参数的StudentDTO类型: using System.Collections.Generic;using System.Threading.Tasks;using AutoMapper;using AutoMapperDemo.DTO;using AutoMapperDemo.Model;using Microsoft.AspNetCore.Mvc;namespace AutoMapperDemo.Controllers{ [Route("api/[controller]")] [ApiController] public class StudentController : ControllerBase { private readonly IMapper _mapper; /// /// 通过构造函数实现依赖注入 /// /// public StudentController(IMapper mapper) { _mapper = mapper; } [HttpGet] public async Task Get() { List list = new List(); list = await Task.Run(() =>

{return Data.GetList ();}); return list;} [HttpGet ("GetDTO")] public async Task GetDto () {List list = new List (); List listStudent = await Task.Run (() = > {return Data.GetList ();}) / assign a value to the property / / foreach (var item in listStudent) / / {/ / StudentDTO dto = new StudentDTO (); / / dto.ID = item.ID; / / dto.Name = item.Name; / / dto.Age = item.Age; / / dto.Gender = item.Gender / add / / list.Add (dto) to the collection; / /} / / use AutoMapper to map list = _ mapper.Map (listStudent); return list;} [HttpPost] public async Task Post ([FromBody] StudentDTO entity) {List list = new List () / / reverse map StudentDTO to Student type Student student = _ mapper.Map (entity); / / add Data.Add (student) to the collection; / / return the added array, where Student list = await Task.Run (() = > {return Data.GetList ()) }); return list;}}

Test with Postman:

Return the result:

In this way, the mapping is reversed.

On "ASP.NET Core how to use AutoMapper to achieve entity mapping" this article is shared here, I hope the above content can be of some help to you, so that you can learn more knowledge, if you think the article is good, please share it out for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report