autobus-api_old/AutobusApi.Application/Buses/Commands/DeleteBus/DeleteBusCommandHandler.cs

34 lines
887 B
C#

using AutobusApi.Application.Common.Exceptions;
using AutobusApi.Application.Common.Interfaces;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace AutobusApi.Application.Buses.Commands.DeleteBus;
public class DeleteBusCommandHandler : IRequestHandler<DeleteBusCommand>
{
private readonly IApplicationDbContext _dbContext;
public DeleteBusCommandHandler(IApplicationDbContext dbContext)
{
_dbContext = dbContext;
}
public async Task Handle(
DeleteBusCommand request,
CancellationToken cancellationToken)
{
var bus = await _dbContext.Buses
.SingleOrDefaultAsync(c => c.Id == request.Id, cancellationToken);
if (bus == null)
{
throw new NotFoundException();
}
_dbContext.Buses.Remove(bus);
await _dbContext.SaveChangesAsync(cancellationToken);
}
}