using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using mongo1.Data; using mongo1.Models; namespace mongo1.Controllers { [Route("[controller]")] [ApiController] public class CommentController : ControllerBase { private readonly ApplicationDbContext _context; public CommentController(ApplicationDbContext context) { _context = context; } [HttpGet] public List GetComments() { var comments = _context.Comments.ToList(); return comments; } [HttpPost] public ActionResult> PostComment([FromBody] Comment comment) { comment.Date = DateTime.Now; _context.Comments.Add(comment); _context.SaveChanges(); var article = _context.Articles.Include(a => a.Comments).SingleOrDefault(a => a.Id == comment.ArticleId); if (article == null) { return NotFound(); } return Ok(article.Comments); } [HttpDelete("{id}")] public List DeleteComment(int id) { var comment = _context.Comments.Find(id); if (comment == null) { return _context.Comments.ToList(); } _context.Comments.Remove(comment); _context.SaveChanges(); return _context.Comments.ToList(); } [HttpGet("{id}")] public ActionResult GetComment(int id) { var comment = _context.Comments.Find(id); if (comment == null) { return NotFound(); } return comment; } [HttpPut("{id}")] public ActionResult> PutComment(int id, [FromBody] Comment updatedComment) { var comment = _context.Comments.Find(id); if (comment == null) { return NotFound(); } comment.Content = updatedComment.Content; _context.Comments.Update(comment); _context.SaveChanges(); return Ok(_context.Comments); } } }