autobus-api_old/AutobusApi.Application/Cities/Commands/DeleteCity/DeleteCityCommandHandler.cs

34 lines
898 B
C#

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