56 lines
1.5 KiB
C#
56 lines
1.5 KiB
C#
using MediatR;
|
|
using cuqmbr.TravelGuide.Application.Common.Persistence;
|
|
using AutoMapper;
|
|
using cuqmbr.TravelGuide.Application.Common.Exceptions;
|
|
|
|
namespace cuqmbr.TravelGuide.Application.Cities.Commands.UpdateCity;
|
|
|
|
public class UpdateCityCommandHandler :
|
|
IRequestHandler<UpdateCityCommand, CityDto>
|
|
{
|
|
private readonly UnitOfWork _unitOfWork;
|
|
private readonly IMapper _mapper;
|
|
|
|
public UpdateCityCommandHandler(
|
|
UnitOfWork unitOfWork,
|
|
IMapper mapper)
|
|
{
|
|
_unitOfWork = unitOfWork;
|
|
_mapper = mapper;
|
|
}
|
|
|
|
public async Task<CityDto> Handle(
|
|
UpdateCityCommand request,
|
|
CancellationToken cancellationToken)
|
|
{
|
|
var entity = await _unitOfWork.CityRepository.GetOneAsync(
|
|
e => e.Guid == request.Guid, e => e.Region.Country,
|
|
cancellationToken);
|
|
|
|
if (entity == null)
|
|
{
|
|
throw new NotFoundException();
|
|
}
|
|
|
|
var parentEntity = await _unitOfWork.RegionRepository.GetOneAsync(
|
|
e => e.Guid == request.RegionGuid, cancellationToken);
|
|
|
|
if (parentEntity == null)
|
|
{
|
|
throw new NotFoundException(
|
|
$"Parent entity with Guid: {request.RegionGuid} not found.");
|
|
}
|
|
|
|
entity.Name = request.Name;
|
|
entity.RegionId = parentEntity.Id;
|
|
|
|
entity = await _unitOfWork.CityRepository.UpdateOneAsync(
|
|
entity, cancellationToken);
|
|
|
|
await _unitOfWork.SaveAsync(cancellationToken);
|
|
_unitOfWork.Dispose();
|
|
|
|
return _mapper.Map<CityDto>(entity);
|
|
}
|
|
}
|