系列導航及源代碼
需求
本文我們繼續來看查詢過程中的另外一個需求:搜索。搜索的含義是目標字段的全部或者部分值匹配請求中的搜索條件,對應到數據庫層面是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的輔助類方法來統一管理類似的需求。