系列導航及源代碼
- 使用.NET 6開發TodoList應用文章索引
需求
本文我們繼續來看查詢程序中的另外一個需求:搜索,搜索的含義是目標欄位的全部或者部分值匹配請求中的搜索條件,對應到資料庫層面是Contains邏輯,實作起來也很簡單,
目標
實作包含搜索條件的查詢,
原理與思路
實作搜索的方式和之前基本思路是一致的,這篇文章大概是這個系列到目前為止最直接和簡單的了,
實作
直接修改上一篇里定義的GetTodoItemsWithConditionQuery,添加一個Title欄位用于搜索:
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.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 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)
{
return await _repository
.GetAsQueryable(x => x.ListId == request.ListId
&& (!request.Done.HasValue || x.Done == request.Done)
&& (!request.PriorityLevel.HasValue || x.Priority == request.PriorityLevel)
&& (string.IsNullOrEmpty(request.Title) || x.Title!.Trim().ToLower().Contains(request.Title!.ToLower())))
.OrderBy(x => x.Title)
.ProjectTo<TodoItemDto>(_mapper.ConfigurationProvider)
.PaginatedListAsync(request.PageNumber, request.PageSize);
}
}
驗證
啟動Api專案,執行查詢TodoItem的請求:
-
請求

-
回應

總結
對于“包含”類的搜索查詢需要注意的是搜索條件的準確性,比如是否允許模糊大小寫,是否采用前綴/后綴匹配,是否涉及到大資料量并且沒有index的多條件搜索(一般在這種情況下,可能需要考慮Elasticsearch等非關系型資料庫存盤來完成搜索查詢),對于普通的場景,實作起來還是比較簡單的,我們也可以定義一些Repository的輔助類方法來統一管理類似的需求,
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/401364.html
標籤:.NET Core
