在控制器方法中,将命令发送到MediatR的代码几乎只有一行:
[HttpPost] public async Task<ActionResult<TodoDTO>> Create(CreateTodoCommand param) { var ret = await mediator.Send(param); return CreatedAtAction(nameof(Get), new { id = ret.Id }, ret); } 3.2 查询 (Query)首先,定义DTO
[Table("T_Todo")] public class TodoDTO { #region Public Properties public Guid Id { get; set; } public string Name { get; set; } #endregion }然后,创建具体的查询方法
public class TodoQueries { private readonly TodoingQueriesContext context; public TodoQueries(TodoingQueriesContext context) { this.context = context; } //... public async Task<PaginatedItems<TodoDTO>> Query(int pageIndex, int pageSize) { var total = await context.Todos .AsNoTracking() .CountAsync(); var todos = await context.Todos .AsNoTracking() .OrderBy(o => o.Id) .Skip(pageSize * (pageIndex - 1)) .Take(pageSize) .ToListAsync(); return new PaginatedItems<TodoDTO>(total, todos); } //... }请注意TodoingQueriesContext和命令处理中的Context不是同一个,实现查询端除了用EFCore、还可以用存储过程、视图、具体化视图或Dapper等等。
最后,调用查询方法
[Route("api/[controller]")] [ApiController] public class TodosController : ControllerBase { private readonly TodoQueries todoQueries; public TodosController(TodoQueries todoQueries) { this.todoQueries = todoQueries ?? throw new ArgumentNullException(nameof(todoQueries)); } //... [HttpGet] public async Task<ActionResult<PaginatedItems<TodoDTO>>> Query(int pageIndex, int pageSize) { return todoQueries.Query(pageIndex, pageSize).Result; } //... }