autobus-api_old/AutobusApi.Application/Addresses/Commands/DeleteAddress/DeleteAddressCommandHandler.cs

34 lines
931 B
C#

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