基于MediatR的Controller如何实现多个ID批量删除功能
具体调整步骤
- 调整控制器接口,兼容单删/新增批量删除端点
// 保留原有单删接口(可选,不需要可直接删除) [HttpDelete("{id:int}")] public async Task<ActionResult> Delete(int id) { await Mediator.Send(new DeleteRoomCommand { Ids = new List<long> { id } }).ConfigureAwait(false); return NoContent(); } // 新增批量删除端点 [HttpDelete("batch")] public async Task<ActionResult> BatchDelete([FromBody] List<long> ids) { await Mediator.Send(new DeleteRoomCommand { Ids = ids }).ConfigureAwait(false); return NoContent(); }
如果不需要保留单删接口,也可以直接修改原有接口入参为ID集合,路由调整为[HttpDelete]配合[FromBody]接收参数即可,不用单独新增batch端点。
- 修改DeleteRoomCommand的字段定义,把单ID改为ID集合
public class DeleteRoomCommand : IRequest { // 替换原有的单个Id属性 public List<long> Ids { get; set; } }
- 重写CommandHandler逻辑,支持批量操作
public class DeleteRoomCommandHandler : IRequestHandler<DeleteRoomCommand> { private readonly IApplicationDbContext _context; public DeleteRoomCommandHandler(IApplicationDbContext context) { _context = context; } public async Task<Unit> Handle(DeleteRoomCommand request, CancellationToken cancellationToken) { // 批量查询所有待删除的实体 var entities = await _context.Rooms .Where(r => request.Ids.Contains(r.Id)) .ToListAsync(cancellationToken) .ConfigureAwait(false); // 可选校验:存在未找到的ID时直接抛出异常,不需要校验可删除这部分逻辑 var foundIds = entities.Select(e => e.Id).ToList(); var missingIds = request.Ids.Except(foundIds).ToList(); if (missingIds.Any()) { throw new NotFoundException(nameof(Room), string.Join(",", missingIds)); } // 批量移除实体,比循环调用Remove效率更高 _context.Rooms.RemoveRange(entities); await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); return Unit.Value; } }
内容的提问来源于stack exchange,提问作者nop
相关产品推荐
相关产品推荐

