|
1 | | -using Microsoft.EntityFrameworkCore; |
| 1 | +using Microsoft.EntityFrameworkCore; |
2 | 2 | using System; |
3 | 3 | using System.Collections.Generic; |
4 | 4 | using System.Linq; |
@@ -28,40 +28,44 @@ string ProductCategory |
28 | 28 |
|
29 | 29 | public record GetCustomerOrdersArgs(int CustomerId, int Offset, int Limit); |
30 | 30 |
|
| 31 | + /// <summary> |
| 32 | + /// Get customer orders with all order items and product details, ordered by date descending with pagination |
| 33 | + /// </summary> |
31 | 34 | public async Task<List<GetCustomerOrdersRow>> GetCustomerOrders(GetCustomerOrdersArgs args) |
32 | 35 | { |
33 | | - var query = _dbContext.Orders |
34 | | - .Where(o => o.CustomerId == args.CustomerId) |
35 | | - .OrderByDescending(o => o.OrderedAt) |
36 | | - .Skip(args.Offset) |
37 | | - .Take(args.Limit); |
| 36 | + var ordersQuery = _dbContext.Orders.AsQueryable(); |
| 37 | + var orderItemsQuery = _dbContext.OrderItems.AsQueryable(); |
| 38 | + var productsQuery = _dbContext.Products.AsQueryable(); |
38 | 39 |
|
39 | 40 | if (!_useTracking) |
40 | | - query = query.AsNoTracking(); |
41 | | - |
42 | | - var results = await query |
43 | | - .SelectMany(o => o.OrderItems.Select(i => new |
44 | | - { |
45 | | - Order = o, |
46 | | - OrderItem = i, |
47 | | - Product = i.Product, |
48 | | - })) |
49 | | - .Select(x => new GetCustomerOrdersRow( |
50 | | - x.Order.OrderId, |
51 | | - x.Order.OrderedAt, |
52 | | - x.Order.OrderState, |
53 | | - x.Order.TotalAmount, |
54 | | - x.OrderItem.OrderItemId, |
55 | | - x.OrderItem.Quantity, |
56 | | - x.OrderItem.UnitPrice, |
57 | | - x.Product.ProductId, |
58 | | - x.Product.Name, |
59 | | - x.Product.Category |
60 | | - )) |
61 | | - .ToListAsync(); |
| 41 | + { |
| 42 | + ordersQuery = ordersQuery.AsNoTracking(); |
| 43 | + orderItemsQuery = orderItemsQuery.AsNoTracking(); |
| 44 | + productsQuery = productsQuery.AsNoTracking(); |
| 45 | + } |
| 46 | + |
| 47 | + var results = await (from o in ordersQuery |
| 48 | + join i in orderItemsQuery on o.OrderId equals i.OrderId |
| 49 | + join p in productsQuery on i.ProductId equals p.ProductId |
| 50 | + where o.CustomerId == args.CustomerId |
| 51 | + orderby o.OrderedAt descending |
| 52 | + select new GetCustomerOrdersRow( |
| 53 | + o.OrderId, |
| 54 | + o.OrderedAt, |
| 55 | + o.OrderState, |
| 56 | + o.TotalAmount, |
| 57 | + i.OrderItemId, |
| 58 | + i.Quantity, |
| 59 | + i.UnitPrice, |
| 60 | + p.ProductId, |
| 61 | + p.Name, |
| 62 | + p.Category |
| 63 | + )) |
| 64 | + .Skip(args.Offset) |
| 65 | + .Take(args.Limit) |
| 66 | + .ToListAsync(); |
62 | 67 | return results; |
63 | 68 | } |
64 | | - |
65 | 69 | public record AddProductsArgs(string Name, string Category, decimal UnitPrice, int StockQuantity, string? Description); |
66 | 70 |
|
67 | 71 | public async Task AddProducts(List<AddProductsArgs> args) |
|
0 commit comments