Ejemplo n.º 1
0
        public async Task <bool> UpdateProductAsync(ProductForEditDto product)
        {
            var productFromRepo = await _context.Products
                                  .SingleOrDefaultAsync(p => p.Id == product.Id);

            if (productFromRepo == null)
            {
                return(false);
            }

            productFromRepo.Update(product);
            return(true);
        }
Ejemplo n.º 2
0
        public async Task <IActionResult> Edit(int id, [FromForm] ProductForEditDto product)
        {
            if (product == null)
            {
                return(BadRequest());
            }

            if (ModelState.IsValid)
            {
                var user = await _userManager.GetUserAsync(HttpContext.User);

                var productFromRepo = await _productRepository.GetProductForUserAsync(user.Id, product.Id);

                if (productFromRepo == null)
                {
                    //Either productId does not belong to user, or productId doesn't exist, or product has been deleted before the form was submitted
                    _flashMessage.Info($"Product no longer exists: {product.Id}");
                    ViewData["updatedVersion"] = null;
                    return(View());
                }

                var timeDifference = Math.Abs((productFromRepo.UpdatedAt - product.UpdatedAt).TotalMilliseconds);
                if (timeDifference > Constants.ConcurrencyMilliseconds)
                {
                    // Someone else has updated the product in the database
                    ViewData["updatedVersion"] = productFromRepo;
                    return(View());
                }

                try
                {
                    await _productRepository.UpdateProductAsync(product);

                    await _productRepository.SaveChanges();

                    _flashMessage.Info($"Successfully updated product: {productFromRepo.ProductName}");

                    await _cachingProductStore.InvalidateCache(product.Id, user.Id);

                    return(RedirectToAction(nameof(Details), new { id = productFromRepo.Id }));
                }
                catch (DbUpdateException)
                {
                    ModelState.AddModelError("", "Unable to save changes.");
                }
            }
            return(View());
        }