/
NikitaMalyshko
/
TaskManager
Обзор
Документация
Войти
/
NikitaMalyshko
/
TaskManager
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
Аналитика
Безопасность
main
Controllers/API/CategoriesController.cs
105 строк
3 KB
Nikita Malyshko
Initial commit - TaskFlow - менеджер задач с Web API и MVC интерфейсом
25 апр 2026, 02:30
25 апр 2026, 02:30
4ff0625
Код
Авторство
О чём код?
using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using TaskManager.Data; using TaskManager.Models; namespace TaskManager.Controllers.API; [Route("api/[controller]")] [ApiController] public class CategoriesController : ControllerBase { private readonly AppDbContext _context; public CategoriesController(AppDbContext context) { _context = context; } // GET: api/categories [HttpGet] public async Task<ActionResult<IEnumerable<Category>>> GetCategories() { return await _context.Categories.ToListAsync(); } // GET: api/categories/5 [HttpGet("{id}")] public async Task<ActionResult<Category>> GetCategory(int id) { var category = await _context.Categories.FindAsync(id); if (category == null) { return NotFound(); } return category; } // POST: api/categories [HttpPost] public async Task<ActionResult<Category>> CreateCategory(Category category) { _context.Categories.Add(category); await _context.SaveChangesAsync(); return CreatedAtAction(nameof(GetCategory), new { id = category.Id }, category); } // PUT: api/categories/5 [HttpPut("{id}")] public async Task<IActionResult> UpdateCategory(int id, Category category) { if (id != category.Id) { return BadRequest("ID в URL не совпадает с ID в теле запроса"); } _context.Entry(category).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!await CategoryExists(id)) { return NotFound(); } throw; } return NoContent(); } // DELETE: api/categories/5 [HttpDelete("{id}")] public async Task<IActionResult> DeleteCategory(int id) { var category = await _context.Categories.FindAsync(id); if (category == null) { return NotFound(); } // Проверяем, есть ли задачи с этой категорией var hasTasks = await _context.Tasks.AnyAsync(t => t.CategoryId == id); if (hasTasks) { // Можно либо запретить удаление, либо установить CategoryId в null // В нашем случае OnDelete(DeleteBehavior.SetNull) в DbContext уже настроен } _context.Categories.Remove(category); await _context.SaveChangesAsync(); return NoContent(); } private async Task<bool> CategoryExists(int id) { return await _context.Categories.AnyAsync(e => e.Id == id); } }