コード例 #1
0
        public IActionResult AddComment([FromBody] CommentSaveDto commentSave)
        {
            var result = _commentService.AddComment(commentSave);

            if (!result.Success)
            {
                return(BadRequest(result.Message));
            }

            return(Ok(result.Comment));
        }
コード例 #2
0
        public CommentResponse AddComment(CommentSaveDto comment)
        {
            Dictionary <string, string[]> errors = new Dictionary <string, string[]>();

            UserAccount user = _context.UserAccounts.FirstOrDefault(u => u.UserName == _userName);

            if (user == null)
            {
                errors.Add("Konto", new[] { "Podane konto nie istnieje" });
                return(new CommentResponse(errors));
            }
            Movie movie = _context.Movies.FirstOrDefault(m => m.MovieId == comment.MovieId);

            if (movie == null)
            {
                errors.Add("Film", new[] { "Podany film nie istnieje" });
                return(new CommentResponse(errors));
            }
            Comment userComment = _context.Comments.FirstOrDefault(u => u.UserName == _userName);

            if (userComment != null)
            {
                errors.Add("Komentarz", new[] { "Dodałej juz ocene do tego filmu " });
                return(new CommentResponse(errors));
            }
            try
            {
                Comment commentSave = _mapper.Map <CommentSaveDto, Comment>(comment);
                commentSave.UserName = user.UserName;
                _context.Comments.Add(commentSave);
                _context.SaveChanges();
                var   movies = _context.Comments.Where(m => m.MovieId == comment.MovieId).ToArray();
                float ratio  = 0;
                for (int i = 0; i < movies.Count(); i++)
                {
                    ratio += movies[i].Ratio;
                }
                ratio      /= movies.Count();
                movie.Ratio = ratio;
                _context.Movies.Update(movie);
                _context.SaveChanges();
                return(new CommentResponse(commentSave));
            }
            catch (Exception ex)
            {
                errors.Add("Wystąpił nieoczekiwany błąd", new[] { ex.Message });
                return(new CommentResponse(errors));
            }
        }