public async Task <IActionResult> Create(int[] SelectedSuppliers, [Bind("ProductID,SKU,ProductName,ProductPrice,ProductDescription")] Product product) { if (ModelState.IsValid) { //Generate the next SKU number product.SKU = GenerateSKU.GetNextSKU(_context); _context.Add(product); await _context.SaveChangesAsync(); //add connections to suppliers //first, find the product you just added Product dbProduct = _context.Products.FirstOrDefault(c => c.SKU == product.SKU); //loop through selected suppliers and add them foreach (int i in SelectedSuppliers) { Supplier dbSup = _context.Suppliers.Find(i); ProductSupplier cd = new ProductSupplier(); cd.Product = dbProduct; cd.Supplier = dbSup; _context.ProductSuppliers.Add(cd); _context.SaveChanges(); } return(RedirectToAction(nameof(Index))); } //repopulate the Viewbag ViewBag.AllSuppliers = GetAllSuppliers(); return(View(product)); }
public IActionResult Create(int[] SelectedSuppliers, [Bind("ProductID,SKU,ProductName,ProductPrice,Description")] Product product) { if (ModelState.IsValid) { product.SKU = GenerateSKU.GetNextSKU(_context); _context.Add(product); _context.SaveChanges(); Product dbProduct = _context.Products.FirstOrDefault(p => p.SKU == product.SKU); foreach (int i in SelectedSuppliers) { Supplier dbSupplier = _context.Suppliers.Find(i); SupplierDetail sd = new SupplierDetail(); sd.Product = dbProduct; sd.Supplier = dbSupplier; _context.SupplierDetails.Add(sd); _context.SaveChanges(); } return(RedirectToAction(nameof(Index))); } ViewBag.AllSuppliers = GetAllSuppliers(); return(View(product)); }