autobus-api_old/AutobusApi.Application/Routes/Commands/DeleteRoute/DeleteRouteCommandHandler.cs

34 lines
906 B
C#

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