这篇文章主要讲解了“.NET 6开发TodoList应用怎么实现查询排序”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“.NET 6开发TodoList应用怎么实现查询排序”吧!
需求
关于查询的另一个需求是要根据前端请求的排序字段进行对结果相应的排序。
目标
实现根据排序要求返回排序后的结果
原理与思路
要实现根据前端请求的进行相应排序,结合我们之前写好的Specification
,可以比较简单地做到。
实现
我们还是用TodoItem
请求来举例,再添加一个排序字段到查询请求中:
GetTodoItemsWithConditionQuery.cs
using AutoMapper;using AutoMapper.QueryableExtensions;using MediatR;using TodoList.Application.Common.Interfaces;using TodoList.Application.Common.Mappings;using TodoList.Application.Common.Models;using TodoList.Application.TodoItems.Specs;using TodoList.Domain.Entities;using TodoList.Domain.Enums;namespace TodoList.Application.TodoItems.Queries.GetTodoItems;public class GetTodoItemsWithConditionQuery : IRequest<PaginatedList<TodoItemDto>>{ public Guid ListId { get; set; } public bool? Done { get; set; } public string? Title { get; set; } public PriorityLevel? PriorityLevel { get; set; } public string? SortOrder { get; set; } = "title_asc"; public int PageNumber { get; set; } = 1; public int PageSize { get; set; } = 10;}public class GetTodoItemsWithConditionQueryHandler : IRequestHandler<GetTodoItemsWithConditionQuery, PaginatedList<TodoItemDto>>{ private readonly IRepository<TodoItem> _repository; private readonly IMapper _mapper; public GetTodoItemsWithConditionQueryHandler(IRepository<TodoItem> repository, IMapper mapper) { _repository = repository; _mapper = mapper; } public async Task<PaginatedList<TodoItemDto>> Handle(GetTodoItemsWithConditionQuery request, CancellationToken cancellationToken) { var spec = new TodoItemSpec(request); return await _repository .GetAsQueryable(spec) .ProjectTo<TodoItemDto>(_mapper.ConfigurationProvider) .PaginatedListAsync(request.PageNumber, request.PageSize); }}
同时把原本写在查询中的条件整合到了TodoItemSpec
中:
TodoItemSpec.cs
// 省略其他...public TodoItemSpec(GetTodoItemsWithConditionQuery query) : base(x => x.ListId == query.ListId && (!query.Done.HasValue || x.Done == query.Done) && (!query.PriorityLevel.HasValue || x.Priority == query.PriorityLevel) && (string.IsNullOrEmpty(query.Title) || x.Title!.Trim().ToLower().Contains(query.Title!.ToLower()))){ if (string.IsNullOrEmpty(query.SortOrder)) return; switch (query.SortOrder) { // 仅作有限的演示 default: ApplyOrderBy(x => x.Title!); break; case "title_desc": ApplyOrderByDescending(x =>x .Title!); break; case "priority_asc": ApplyOrderBy(x => x.Priority); break; case "priority_desc": ApplyOrderByDescending(x => x.Priority); break; }}
验证
启动Api项目,执行查询TodoItem的请求:
请求
响应
感谢各位的阅读,以上就是“.NET 6开发TodoList应用怎么实现查询排序”的内容了,经过本文的学习后,相信大家对.NET 6开发TodoList应用怎么实现查询排序这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是编程网,小编将为大家推送更多相关知识点的文章,欢迎关注!