using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Newtonsoft.Json; using StudyLib.API.Data; using StudyLib.Models; namespace StudyLib.API.Controllers { [Route("api/[controller]")] [ApiController] public class SubjectsController : ControllerBase { private readonly StudyLibContext _context; public SubjectsController(StudyLibContext context) { _context = context; } // GET: api/Subjects [HttpGet] public async Task>> GetSubjects() { return await _context.Subjects.Include(s => s.Comments).Include(s => s.Assignments).Include(s => s.Tests).ToListAsync(); } // GET: api/Subjects/5 [HttpGet("{id}")] public async Task> GetSubject(long id) { var subject = await _context.Subjects.Where(s => s.ID == id).Include(s => s.Comments).Include(s => s.Assignments).Include(s => s.Tests).SingleOrDefaultAsync(); if (subject == null) { return NotFound(); } return subject; } // PUT: api/Subjects/5 // To protect from overposting attacks, enable the specific properties you want to bind to, for // more details, see https://go.microsoft.com/fwlink/?linkid=2123754. [HttpPut("{id}")] public async Task PutSubject(long id, Subject subject) { if (id != subject.ID) { return BadRequest(); } _context.Entry(subject).State = EntityState.Modified; foreach (var comment in subject.Comments) { if (comment.ID >= 1) { _context.Entry(comment).State = EntityState.Modified; } else { _context.Comments.Add(comment); } } foreach (var assignment in subject.Assignments) { if (assignment.ID >= 1) { _context.Entry(assignment).State = EntityState.Modified; } else { _context.Assignments.Add(assignment); } } foreach (var test in subject.Tests) { if (test.ID >= 1) { _context.Entry(test).State = EntityState.Modified; } else { _context.Tests.Add(test); } } try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!SubjectExists(id)) { return NotFound(); } else { throw; } } return NoContent(); } // POST: api/Subjects // To protect from overposting attacks, enable the specific properties you want to bind to, for // more details, see https://go.microsoft.com/fwlink/?linkid=2123754. [HttpPost] public async Task> PostSubject(Subject subject) { _context.Subjects.Add(subject); await _context.SaveChangesAsync(); return CreatedAtAction("GetSubject", new { id = subject.ID }, subject); } // DELETE: api/Subjects/5 [HttpDelete("{id}")] public async Task> DeleteSubject(long id) { var subject = await _context.Subjects.FindAsync(id); if (subject == null) { return NotFound(); } _context.Subjects.Remove(subject); await _context.SaveChangesAsync(); return subject; } private bool SubjectExists(long id) { return _context.Subjects.Any(e => e.ID == id); } } }