autobus-api_old/AutobusApi.Application/Buses/Queries/GetBus/GetBusQueryHandler.cs

39 lines
994 B
C#

using AutobusApi.Application.Common.Exceptions;
using AutobusApi.Application.Common.Interfaces;
using AutoMapper;
using AutoMapper.QueryableExtensions;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace AutobusApi.Application.Buses.Queries.GetBus;
public class GetBusQueryHandler : IRequestHandler<GetBusQuery, BusDto>
{
private readonly IApplicationDbContext _dbContext;
private readonly IMapper _mapper;
public GetBusQueryHandler(
IApplicationDbContext dbContext,
IMapper mapper)
{
_dbContext = dbContext;
_mapper = mapper;
}
public async Task<BusDto> Handle(
GetBusQuery request,
CancellationToken cancellationToken)
{
var bus = await _dbContext.Buses
.ProjectTo<BusDto>(_mapper.ConfigurationProvider)
.SingleOrDefaultAsync(c => c.Id == request.Id);
if (bus == null)
{
throw new NotFoundException();
}
return bus;
}
}