// GET: Products/Edit/5 public ActionResult Edit(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } List<Product> products = GetProductsIncludingImages(); if(products == null) { return HttpNotFound(); } ProductCreateEditViewModel productEditViewModel = new ProductCreateEditViewModel() { Product = products.Where(p => p.ProductId == id).FirstOrDefault() }; if (productEditViewModel == null) { return HttpNotFound(); } ViewBag.Categories = new SelectList(db.Categories.OrderBy(g => g.CategoryName), "CategoryId", "CategoryName", productEditViewModel.Product.CategoryId); return View(productEditViewModel); }
private void AddImageToProduct(ProductCreateEditViewModel productCreateEditViewModel) { using (var dbContextTransaction = db.Database.BeginTransaction()) { try { foreach (HttpPostedFileBase imageString in productCreateEditViewModel.ImageStrings) { byte[] encodedImage = Helper.ConvertHttpPostedFileBaseToByteArray(imageString); int imageId; // Add the image to the images table if it doesn't exist in the db yet. if (!db.Images.Where(i => i.EncodedImage == encodedImage).Any()) { // Create the new id of the images table. imageId = db.Images.Any() ? db.Images.Max(c => c.ImageId) + 1 : 1; db.Images.Add(new Image() { ImageId = imageId, EncodedImage = encodedImage }); db.SaveChanges(); } else { // Get the already existing imageId that corresponds to the picture that is to be added. imageId = db.Images.Where(i => i.EncodedImage == encodedImage).FirstOrDefault().ImageId; } // Add a record to the ImageProduct junction table. db.ImageProducts.Add(new ImageProduct() { ImageId = imageId, ProductId = productCreateEditViewModel.Product.ProductId }); db.SaveChanges(); dbContextTransaction.Commit(); } } catch (Exception) { dbContextTransaction.Rollback(); } } }