public async Task <IActionResult> Update([FromForm] ProductModel model) { var server = _productService.CreateInstance(); if (server != null) { if (!User.Identity.IsAuthenticated) { return(Unauthorized()); } if (!User.IsInRole("Admin")) { return(Unauthorized()); } var user = await _userManager.GetUserAsync(User); var transaction = _productService.Transaction(server); try { var product = _productService.FindById(model.Id); if (product == null) { return(NotFound()); } var uploadResult = new ImageUploadResult(); if (model.Image != null) { using (var stream = model.Image.OpenReadStream()) { _cloudinary.DeleteResources(ResourceType.Image, product.ImageId); var uploadParams = new ImageUploadParams { File = new FileDescription(model.Image.Name, stream), Folder = "Products" }; uploadResult = _cloudinary.Upload(uploadParams); } } product.Description = model.Description; product.ImageId = uploadResult.PublicId != null ? uploadResult.PublicId : product.ImageId; product.Image = uploadResult.SecureUrl != null?uploadResult.SecureUrl.ToString() : product.Image; product.Name = model.Name; product.Price = Convert.ToDecimal(model.Price); product.Quantity = int.Parse(model.Quantity); product.Availability = product.Quantity > 0 ? true : false; product.Weight = Convert.ToDecimal(model.Weight); product.UpdateUser = user.UserName; product.UpdateDate = DateTime.Now; var newProduct = _productService.Update(product); List <string> categoryList = new List <string>(); if (model.CategoryId[0] != null) { _productCategories.CreateInstance(instance: true, context: server); var pCList = _productCategories.GetAll(c => c.Products_Id == newProduct.Id); _productCategories.RemoveRange(pCList); categoryList.AddRange(model.CategoryId.SelectMany(c => c.Split(",")).ToList()); newProduct.ProductsCategories = categoryList.Select(c => new ProductCategories { Categories_Id = int.Parse(c), Products_Id = newProduct.Id }).ToList(); _productCategories.AddRange(newProduct.ProductsCategories); } transaction.Commit(); return(Ok()); } catch (Exception e) { transaction.Dispose(); var error = e.InnerException != null ? e.InnerException.Message : e.Message; var response = new { error = error }; return(StatusCode(512, response)); } } return(StatusCode(423)); }