DemO/DEMO/Controllers/OrderItemsController.cs

78 lines
2.4 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// товары внутри заказов
using DEMO.Data; // база
using DEMO.Models; // позиции заказа
using Microsoft.AspNetCore.Mvc; // контроллер
using Microsoft.EntityFrameworkCore; // база
namespace DEMO.Controllers;
[ApiController] // это api
[Route("api/[controller]")] // адрес будет api/orderitems
public class OrderItemsController : ControllerBase
{
private readonly AppDbContext _context; // база
// запоминаю базу
public OrderItemsController(AppDbContext context)
{
_context = context;
}
// отдать все позиции
[HttpGet]
public async Task<IActionResult> GetOrderItems()
{
// беру позиции и сразу заказ и товар
var orderItems = await _context.OrderItems
.Include(i => i.Order)
.Include(i => i.Product)
.ToListAsync();
return Ok(orderItems);
}
// добавить товар в заказ
[HttpPost]
public async Task<IActionResult> CreateOrderItem(OrderItem orderItem) // приходит заказ товар колво цена
{
_context.OrderItems.Add(orderItem); // добавляю
await _context.SaveChangesAsync(); // сохраняю
return Ok(orderItem);
}
// изменить позицию
[HttpPut("{id}")]
public async Task<IActionResult> UpdateOrderItem(int id, OrderItem orderItem)
{
var existingItem = await _context.OrderItems.FindAsync(id); // ищу старую
if (existingItem == null)
return NotFound();
// меняю поля
existingItem.OrderId = orderItem.OrderId;
existingItem.ProductId = orderItem.ProductId;
existingItem.Quantity = orderItem.Quantity;
existingItem.Price = orderItem.Price;
await _context.SaveChangesAsync(); // сохраняю
return Ok(existingItem);
}
// удалить позицию
[HttpDelete("{id}")]
public async Task<IActionResult> DeleteOrderItem(int id)
{
var orderItem = await _context.OrderItems.FindAsync(id); // ищу
if (orderItem == null)
return NotFound();
_context.OrderItems.Remove(orderItem); // удаляю
await _context.SaveChangesAsync(); // сохраняю
return NoContent();
}
}