很直接的問題。我希望能夠洗掉多個 ID,就像下面的示例一樣。
public async Task<ActionResult> Delete(List<int> id)`
片段
[HttpDelete("{id:int}")]
public async Task<ActionResult> Delete(int id)
{
await Mediator.Send(new DeleteRoomCommand { Id = id }).ConfigureAwait(false);
return NoContent();
}
public class DeleteRoomCommand : IRequest
{
public long Id { get; set; }
}
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 entity = await _context.Rooms.FindAsync(request.Id).ConfigureAwait(false);
if (entity == null)
{
throw new NotFoundException(nameof(Room), request.Id);
}
_context.Rooms.Remove(entity);
await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
return Unit.Value;
}
}
uj5u.com熱心網友回復:
你似乎在問兩個問題:
如何為 MediatR 撰寫一個新的命令和處理程式,以接受和傳遞可列舉的 ID 而不僅僅是一個?
如何撰寫 DbContext 呼叫來處理該可列舉項?
IRequest 物件只是一個簡單的類,其中包含處理它所需的資料。您可以創建一個新的復數命令類,它接受可列舉的 ID,以及一個旨在處理這種情況的新處理程式。您需要根據自己的測驗對此進行調整。
public class DeleteRoomsCommand : IRequest
{
public IEnumerable<long> Ids { get; set; }
}
public class DeleteRoomsCommandHandler : IRequestHandler<DeleteRoomsCommand>
{
private readonly IApplicationDbContext _context;
public DeleteRoomCommandHandler(IApplicationDbContext context)
{
_context = context;
}
public async Task<Unit> Handle(DeleteRoomsCommand request, CancellationToken cancellationToken)
{
var entities = await _context.Rooms.Where(r => request.Ids.Contains(r.Id)); // .ConfigureAwait(false);
_context.Rooms.RemoveRange(entities);
await _context.SaveChangesAsync(cancellationToken); // .ConfigureAwait(false);
return Unit.Value;
}
}
你的新呼叫同樣被實體化,獲取你的控制器收到的 ID 并將它們分配給一個新的 MediatR 命令:
await Mediator.Send(new DeleteRoomsCommand { Ids = ids }); //.ConfigureAwait(false);
您的新方法可以通過查詢引數或通過正文接受 ID 串列,具體取決于您的需要或約定。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/347657.html
