forked from MicrosoftDocs/mslearn-blazor-navigation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
OrderController.cs
69 lines (57 loc) · 2.08 KB
/
OrderController.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace BlazingPizza;
[Route("orders")]
[ApiController]
public class OrdersController : Controller
{
private readonly PizzaStoreContext _db;
public OrdersController(PizzaStoreContext db)
{
_db = db;
}
[HttpGet]
public async Task<ActionResult<List<OrderWithStatus>>> GetOrders()
{
var orders = await _db.Orders
.Include(o => o.Pizzas).ThenInclude(p => p.Special)
.Include(o => o.Pizzas).ThenInclude(p => p.Toppings).ThenInclude(t => t.Topping)
.OrderByDescending(o => o.CreatedTime)
.ToListAsync();
return orders.Select(o => OrderWithStatus.FromOrder(o)).ToList();
}
[HttpPost]
public async Task<ActionResult<int>> PlaceOrder(Order order)
{
order.CreatedTime = DateTime.Now;
// Enforce existence of Pizza.SpecialId and Topping.ToppingId
// in the database - prevent the submitter from making up
// new specials and toppings
foreach (var pizza in order.Pizzas)
{
pizza.SpecialId = pizza.Special.Id;
pizza.Special = null;
}
_db.Orders.Attach(order);
await _db.SaveChangesAsync();
return order.OrderId;
}
//Método para devolver un pedido
//Este código permitía al controlador de pedidos responder a una solicitud HTTP con orderId en la URL.
// A continuación, el método utiliza este identificador para consultar la base de datos y, si se encuentra un pedido,
//devolver un objeto.OrderWithStatus
[HttpGet("{orderId}")]
public async Task<ActionResult<OrderWithStatus>> GetOrderWithStatus(int orderId)
{
var order = await _db.Orders
.Where(o => o.OrderId == orderId)
.Include(o => o.Pizzas).ThenInclude(p => p.Special)
.Include(o => o.Pizzas).ThenInclude(p => p.Toppings).ThenInclude(t => t.Topping)
.SingleOrDefaultAsync();
if (order == null)
{
return NotFound();
}
return OrderWithStatus.FromOrder(order);
}
}