DemO/DEMO/Controllers/ProductsController.cs

86 lines
2.7 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/products
public class ProductsController : ControllerBase
{
private readonly AppDbContext _context; // база
// запоминаю базу
public ProductsController(AppDbContext context)
{
_context = context;
}
// отдать все товары, GET api/products
[HttpGet]
public async Task<IActionResult> GetProducts()
{
// беру товары и сразу их категории
var products = await _context.Products
.Include(p => p.Category)
.ToListAsync();
return Ok(products); // отдаю список
}
// добавить товар, POST api/products
[HttpPost]
public async Task<IActionResult> CreateProduct(Product product) // приходит товар
{
// проверяю есть ли такая категория
var categoryExists = await _context.Categories
.AnyAsync(c => c.Id == product.CategoryId);
if (!categoryExists)
return BadRequest("Такой категории нет.");
_context.Products.Add(product); // добавляю
await _context.SaveChangesAsync(); // сохраняю
return Ok(product); // отдаю обратно
}
// изменить товар, PUT api/products/5
[HttpPut("{id}")]
public async Task<IActionResult> UpdateProduct(int id, Product product)
{
// ищу старый товар
var existingProduct = await _context.Products.FindAsync(id);
if (existingProduct == null)
return NotFound(); // нет такого
// меняю поля
existingProduct.Name = product.Name;
existingProduct.Price = product.Price;
existingProduct.CategoryId = product.CategoryId;
await _context.SaveChangesAsync(); // сохраняю
return Ok(existingProduct);
}
// удалить товар, DELETE api/products/5
[HttpDelete("{id}")]
public async Task<IActionResult> DeleteProduct(int id)
{
// ищу товар
var product = await _context.Products.FindAsync(id);
if (product == null)
return NotFound();
_context.Products.Remove(product); // удаляю
await _context.SaveChangesAsync(); // сохраняю
return NoContent(); // все хорошо, отдавать нечего
}
}