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 use AutoMapper to implement GET requests

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

Share

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

This article mainly explains "how to use AutoMapper to achieve GET request". The content of the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to use AutoMapper to achieve GET request".

Demand

The requirement is simple: implement the GET request to get the business data. The class library we often use at this stage is AutoMapper.

target

Organize and use AutoMapper reasonably to complete GET request.

Principles and ideas

First of all, let's briefly introduce this class library.

About AutoMapper

An essential part of the process of business-side code dealing with database entities is the returned data type conversion. For different requests, the desired return value is part of the database entity / combination / calculation, and so on. We often need handwritten code for data object conversion, but there may be fields or properties with the same name in most cases before and after the conversion. Can this part of the work avoid lengthy handwritten code? Sure.

The request we want to accept and the value returned (collectively referred to as model) have two principles to follow:

1. Each model is consumed by and only by one API

two。 Each model contains only the necessary fields or attributes that the API initiator wants to include.

The AutoMapper library exists to implement this requirement, and for its specific use, please refer to the official documentation, especially the section on Convention, to avoid duplication of effort.

Realize

All the areas where you need to use AutoMapper are concentrated in the Application project.

Introduction of AutoMapper$ dotnet add src/TodoList.Application/TodoList.Application.csproj package AutoMapper.Extensions.Microsoft.DependencyInjection

Then add the configuration under Application/Common/Mappings to provide the interface because we can implement the corresponding Mapping rules in DTO later, which is easy to find.

IMapFrom.cs

Using AutoMapper;namespace TodoList.Application.Common.Mappings;public interface IMapFrom {void Mapping (Profile profile) = > profile.CreateMap (typeof (T), GetType ();}

MappingProfile.cs

Using System.Reflection;using AutoMapper;namespace TodoList.Application.Common.Mappings;public class MappingProfile: Profile {public MappingProfile () = > ApplyMappingsFromAssembly (Assembly.GetExecutingAssembly ()); private void ApplyMappingsFromAssembly (Assembly assembly) {var types = assembly.GetExportedTypes () .Where (t = > t.GetInterfaces () .Any (I = > i.IsGenericType & & i.GetGenericTypeDefinition () = = typeof (IMapFrom) .ToList () Foreach (var type in types) {var instance = Activator.CreateInstance (type); var methodInfo = type.GetMethod ("Mapping")? Type.GetInterface ("IMapFrom`1")! .GetMethod ("Mapping"); methodInfo?.Invoke (instance, new object [] {this});}

Do dependency injection in DependencyInjection.cs:

DependencyInjection.cs

/ / omit other... services.AddAutoMapper (Assembly.GetExecutingAssembly ()); services.AddMediatR (Assembly.GetExecutingAssembly ()); return services; implements the GET request

In this chapter, we only implement TodoList's Query interface (GET), and include the TodoItem collection in the results, which are covered step by step in the remaining interfaces.

GET All TodoLists

Create a new directory under Application/TodoLists/Queries/ GetTodos to store all the logic related to creating a TodoList:

Define the TodoListBriefDto object:

TodoListBriefDto.cs

Using TodoList.Application.Common.Mappings;namespace TodoList.Application.TodoLists.Queries.GetTodos;// implements the IMapFrom interface because this Dto does not involve Mapping rules of special fields and the attribute names are consistent with domain entities. According to Convention rules, Mapping can be completed by default without additional implementation of public class TodoListBriefDto: IMapFrom {public Guid Id {get; set;} public string? Title {get; set;} public string? Colour {get; set;}}

GetTodosQuery.cs

Using AutoMapper;using AutoMapper.QueryableExtensions;using MediatR;using Microsoft.EntityFrameworkCore;using TodoList.Application.Common.Interfaces;namespace TodoList.Application.TodoLists.Queries.GetTodos;public class GetTodosQuery: IRequest {} public class GetTodosQueryHandler: IRequestHandler {private readonly IRepository _ repository; private readonly IMapper _ mapper; public GetTodosQueryHandler (IRepository repository, IMapper mapper) {_ repository = repository; _ mapper = mapper } public async Task Handle (GetTodosQuery request, CancellationToken cancellationToken) {return await _ repository .GetAsQueryable () .AsNoTracking () .ProjectTo (_ mapper.ConfigurationProvider) .OrderBy (t = > t.Title) .ToListAsync (cancellationToken);}}

Finally, the logic of the Controller layer is implemented:

TodoListController.cs

/ / omit other... [HttpGet] public async Task Get () {return await _ mediator.Send (new GetTodosQuery ());}

GET Single TodoList

First, create a new directory GetTodoItems under Application/TodoItems/Queries/ to store all the logic related to obtaining TodoItem:

Define TodoItemDto and TodoListDto objects:

TodoItemDto.cs

Using AutoMapper;using TodoList.Application.Common.Mappings;using TodoList.Domain.Entities;namespace TodoList.Application.TodoItems.Queries.GetTodoItems;// implements IMapFrom interface public class TodoItemDto: IMapFrom {public Guid Id {get; set;} public Guid ListId {get; set;} public string? Title {get; set;} public bool Done {get; set;} public int Priority {get; set;} / / implements the Mapping method defined by the interface and provides translation rules for special fields other than Convention: public void Mapping (Profile profile) {profile.CreateMap () .ForMember (d = > d.Priority, opt = > opt.MapFrom (s = > (int) s.Priority);}}

TodoListDto.cs

Using TodoList.Application.Common.Mappings;using TodoList.Application.TodoItems.Queries.GetTodoItems;namespace TodoList.Application.TodoLists.Queries.GetSingleTodo;// implements the IMapFrom interface because this Dto does not involve Mapping rules of special fields and the attribute names are consistent with domain entities. According to Convention rules, Mapping can be completed by default without additional implementation of public class TodoListDto: IMapFrom {public Guid Id {get; set;} public string? Title {get; set;} public string? Colour {get; set;} public IList Items {get; set;} = new List ();}

Create a spec that contains TodoItems children according to ListId:

TodoListSpec.cs

Using Microsoft.EntityFrameworkCore;using TodoList.Application.Common;namespace TodoList.Application.TodoLists.Specs;public sealed class TodoListSpec: SpecificationBase {public TodoListSpec (Guid id, bool includeItems = false): base (t = > t.Id = = id) {if (includeItems) {AddInclude (t = > t.Include (I = > i.Items));}

We still create a new GetSingleTodo directory for this query and implement GetSIngleTodoQuery:

GetSingleTodoQuery.cs

Using AutoMapper;using AutoMapper.QueryableExtensions;using MediatR;using Microsoft.EntityFrameworkCore;using TodoList.Application.Common.Interfaces;using TodoList.Application.TodoLists.Specs;namespace TodoList.Application.TodoLists.Queries.GetSingleTodo;public class GetSingleTodoQuery: IRequest {public Guid ListId {get; set;}} public class ExportTodosQueryHandler: IRequestHandler {private readonly IRepository _ repository; private readonly IMapper _ mapper; public ExportTodosQueryHandler (IRepository repository, IMapper mapper) {_ repository = repository; _ mapper = mapper } public async Task Handle (GetSingleTodoQuery request, CancellationToken cancellationToken) {var spec = new TodoListSpec (request.ListId, true); return await _ repository .GetAsQueryable (spec) .AsNoTracking () .ProjectTo (_ mapper.ConfigurationProvider) .FirstOrDefaultAsync (cancellationToken);}}

Add Controller logic, the Name here is to complete the previously left problems returned by 201.1, which will be used later.

TodoListController.cs

Omit other... [HttpGet ("{id:Guid}", Name = "TodListById")] public async Task GetSingleTodoList (Guid id) {return await _ mediator.Send (new GetSingleTodoQuery {ListId = id})? Throw new InvalidOperationException ();} Verification

Run the Api project

Get all TodoList lists

Request

Response

Get individual TodoList details

Request

Response

Fill in a hole in a POST article

In developing TodoList applications with .NET 6 (6)-- using MediatR to implement POST requests, we left a problem, that is, the return value after the creation of TodoList was temporarily returned using Id. The recommended practice is as follows:

/ / omit other... [HttpPost] public async Task Create ([FromBody] CreateTodoListCommand command) {var createdTodoList = await _ mediator.Send (command); / / 201 return CreatedAtRoute ("TodListById", new {id = createdTodoList.Id}, createdTodoList) returned after successful creation;}

Request

Return

Content part

And the Header part

Our main observation is that the returned HTTPStatusCode is 201, and the location field in the Header indicates the location where the resource was created.

Thank you for reading, the above is the content of "how to use AutoMapper to achieve GET request". After the study of this article, I believe you have a deeper understanding of how to use AutoMapper to achieve GET request, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

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