using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; using MyRecipes2.Server.Data; using MyRecipes2.Server.Models; using MyRecipes2.Shared; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace MyRecipes2.Server.Controllers { [ApiController] public class CommentController : ControllerBase { private readonly ApplicationDbContext dbContext; public CommentController(ApplicationDbContext dbContext) { this.dbContext = dbContext; } [HttpPost] [Route("[controller]")] public CommentDto Post(CreateCommentRequestDto request) { // Find the recipe Recipe recipe = dbContext.Recipes .Where(x => x.Id == request.RecipeId) .Include(x => x.CreatedBy) .Include(x => x.Ingredients) .Include(x => x.Comments) .Include(x => x.Image) .First(); // Find the application user ApplicationUser user = dbContext.Users.Where(x => x.Id == request.CreatedById).First(); // Create the comment Comment comment = new Comment(); comment.CreatedBy = user; comment.Text = request.Text; comment.Recipe = recipe; comment.CreatedDateTime = DateTime.Now; // add the comment to the recipe recipe.Comments.Add(comment); // save the database dbContext.Comments.Add(comment); dbContext.SaveChanges(); CommentDto result = new(); result.Text = request.Text; result.Time = DateTime.Now.ToString(); result.User = user.UserName; return result; } } }