예제 #1
0
        public async Task <IActionResult> AddComment([FromBody] CommentForCreationDto newComment, int id, int cityId, int placeId)
        {
            var placeFromRepo = await _repository.GetPlaceForCity(cityId, placeId);

            if (placeFromRepo == null)
            {
                return(NotFound());
            }
            var commentToAdd = Mapper.Map <Comment>(newComment);

            commentToAdd.Date = DateTime.Now;
            _repository.AddCommentForPlace(commentToAdd);
            if (!await _repository.Save())
            {
                throw new Exception("Failed");
            }
            var commentsFromRepo = await _repository.GetCommentsForPlace(placeId);

            var avgRating = commentsFromRepo.Average(c => c.Rating);

            placeFromRepo.Rating = avgRating;
            if (!await _repository.Save())
            {
                throw new Exception("Failed");
            }
            var placesFromRepo = await _repository.GetPlacesForCity(cityId);

            avgRating = placesFromRepo.Average(p => p.Rating);
            var cityFromRepo = await _repository.GetCityForCountry(id, cityId);

            cityFromRepo.Rating = avgRating;
            if (!await _repository.Save())
            {
                throw new Exception("Failed");
            }
            var citiesFromRepo = await _repository.GetCitiesForCountry(id);

            avgRating = citiesFromRepo.Average(c => c.Rating);
            var countryFromRepo = await _repository.GetCountry(id);

            countryFromRepo.Rating = avgRating;
            if (!await _repository.Save())
            {
                throw new Exception("Failed");
            }
            return(NoContent());
        }