Skip to content

Instantly share code, notes, and snippets.

@dcomartin
Last active October 26, 2023 19:45
Show Gist options
  • Save dcomartin/098348523e84c1f42ff2cfd06ab1a8bd to your computer and use it in GitHub Desktop.
Save dcomartin/098348523e84c1f42ff2cfd06ab1a8bd to your computer and use it in GitHub Desktop.
public interface IOrderReadService
{
Task<OrderResponse> GetOrderByIdAsync(int orderId);
}
public class OrderReadService : IOrderReadService
{
private readonly OrderContext _context;
public OrderReadService(OrderContext context)
{
_context = context;
}
public async Task<OrderResponse> GetOrderByIdAsync(int orderId)
{
var orderResponse = await _context.Orders
.Where(x => x.OrderId == orderId)
.Select(x => new OrderResponse
{
OrderDate = x.OrderDate,
OrderItems = x.OrderItems.Select(oi => new OrderItemResponse
{
PictureUrl = oi.PictureUrl,
ProductId = oi.ProductId,
ProductName = oi.ProductName,
UnitPrice = oi.UnitPrice,
Units = oi.Units
}).ToList(),
OrderNumber = x.OrderNumber,
ShippingAddress = x.ShippingAddress,
Total = x.Total()
})
.SingleAsync();
return orderResponse;
}
}
public class GetOrderQueryHandler : IRequestHandler<GetOrderQuery, OrderResponse>
{
private readonly IOrderReadService _orderReadService;
public GetOrderQueryHandler(IOrderReadService orderReadService)
{
_orderReadService = orderReadService;
}
public Task<OrderResponse> Handle(GetOrderQuery request, CancellationToken cancellationToken)
{
return _orderReadService.GetOrderByIdAsync(request.OrderId);
}
}
public class OrderController : Controller
{
private readonly IMediator _mediator;
public OrderController(IMediator mediator)
{
_mediator = mediator;
}
public async Task<IActionResult> Detail(int orderId)
{
var viewModel = await _mediator.Send(new GetOrderQuery(orderId));
return View(viewModel);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment