68 lines
2.1 KiB
C#
68 lines
2.1 KiB
C#
// все про категории
|
||
using DEMO.Data; // база
|
||
using DEMO.Models; // категории
|
||
using Microsoft.AspNetCore.Mvc; // контроллер
|
||
using Microsoft.EntityFrameworkCore; // база
|
||
|
||
namespace DEMO.Controllers;
|
||
|
||
[ApiController] // это api
|
||
[Route("api/[controller]")] // адрес будет api/categories
|
||
public class CategoriesController : ControllerBase
|
||
{
|
||
private readonly AppDbContext _context; // база
|
||
|
||
// запоминаю базу
|
||
public CategoriesController(AppDbContext context)
|
||
{
|
||
_context = context;
|
||
}
|
||
|
||
// отдать все категории
|
||
[HttpGet]
|
||
public async Task<IActionResult> GetCategories()
|
||
{
|
||
var categories = await _context.Categories.ToListAsync(); // беру все
|
||
return Ok(categories); // отдаю
|
||
}
|
||
|
||
// добавить категорию
|
||
[HttpPost]
|
||
public async Task<IActionResult> CreateCategory(Category category) // приходит название
|
||
{
|
||
_context.Categories.Add(category); // добавляю
|
||
await _context.SaveChangesAsync(); // сохраняю
|
||
return Ok(category);
|
||
}
|
||
|
||
// изменить категорию
|
||
[HttpPut("{id}")]
|
||
public async Task<IActionResult> UpdateCategory(int id, Category category)
|
||
{
|
||
var existingCategory = await _context.Categories.FindAsync(id); // ищу старую
|
||
|
||
if (existingCategory == null)
|
||
return NotFound(); // нет такой
|
||
|
||
existingCategory.Name = category.Name; // меняю название
|
||
await _context.SaveChangesAsync(); // сохраняю
|
||
|
||
return Ok(existingCategory);
|
||
}
|
||
|
||
// удалить категорию
|
||
[HttpDelete("{id}")]
|
||
public async Task<IActionResult> DeleteCategory(int id)
|
||
{
|
||
var category = await _context.Categories.FindAsync(id); // ищу
|
||
|
||
if (category == null)
|
||
return NotFound();
|
||
|
||
_context.Categories.Remove(category); // удаляю
|
||
await _context.SaveChangesAsync(); // сохраняю
|
||
|
||
return NoContent();
|
||
}
|
||
}
|