Example #1
0
        public async Task <IActionResult> PutRating(RatingUpdateRequest ratingUpdateRequest)
        {
            var transaction = await _context.Database.BeginTransactionAsync();

            try
            {
                var rating = await _context.Ratings.FirstOrDefaultAsync(x => x.ProductId == ratingUpdateRequest.ProductId && x.UserId == ratingUpdateRequest.UserId);

                if (rating == null)
                {
                    return(NotFound());
                }
                rating.Star        = ratingUpdateRequest.Star;
                rating.UpdatedDate = DateTime.Now;
                await _context.SaveChangesAsync();

                var product = await _context.Products.FirstOrDefaultAsync(x => x.ProductId == ratingUpdateRequest.ProductId);

                var listRating = await _context.Ratings.Where(x => x.ProductId == ratingUpdateRequest.ProductId).ToListAsync();

                product.StarRating = Convert.ToInt32(listRating.Sum(x => x.Star) / listRating.Count);

                await _context.SaveChangesAsync();

                await transaction.CommitAsync();
            }
            catch
            {
            }

            return(Accepted());
        }
        public async Task <RatingUpdateRequest> UpdateRating(RatingUpdateRequest ratingUpdateRequest)
        {
            HttpContent httpContent = new StringContent(JsonConvert.SerializeObject(ratingUpdateRequest), Encoding.UTF8, "application/json");
            var         response    = await _httpClient.PutAsync("api/Ratings", httpContent);

            response.EnsureSuccessStatusCode();

            return(await response.Content.ReadAsAsync <RatingUpdateRequest>());
        }
        public async Task <IActionResult> UpdateRating(int id, int star)
        {
            var    claimIdentity       = User.Identity as ClaimsIdentity;
            string userid              = claimIdentity.FindFirst(ClaimTypes.NameIdentifier).Value;
            var    ratingUpdateRequest = new RatingUpdateRequest
            {
                UserId    = userid,
                ProductId = id,
                Star      = star,
            };
            await _ratingApiClient.UpdateRating(ratingUpdateRequest);

            return(RedirectToAction("Detail", "Product", new { id }));
        }