public ActionResult TakeItemInventory(TestItemInventoryVM vm) { InventoryContext db = new InventoryContext(); Inventory inventory = db.Inventories.Find(vm.InventoryId); foreach (var item in vm.RegularlyOrderedProducts) { Product product = db.Products.Find(item.Id); var retrievedInvItem = (from i in db.InventoryItems where i.ProductId == product.Id && i.InventoryId == inventory.Id select i).FirstOrDefault(); InventoryItem invItem = new InventoryItem { Product = product, ProductId = product.Id, Inventory = inventory, InventoryId = inventory.Id, Quantity = item.UnitsInStock }; //Ensure Quantity has changed before trying to set values if (item.UnitsInStock != product.UnitsInStock) { invItem.IsInventoried = true; } //If the InventoryItem is different from what's passed from the view, always take what's passed from the view else if (item.IsInventoried != invItem.IsInventoried) { invItem.IsInventoried = item.IsInventoried; } //Set UnitsInStock on Product product.UnitsInStock = item.UnitsInStock; db.Entry(product).State = EntityState.Modified; //If record exists, update it. if (retrievedInvItem != null) { db.Entry(retrievedInvItem).CurrentValues.SetValues(invItem); } //If record doesn't exist, add it else { db.InventoryItems.Add(invItem); } db.SaveChanges(); } return RedirectToAction("TakeInventory"); }
// // GET: /Inventory/TakeItemInventory public ActionResult TakeItemInventory(int inventoryId, int testId) { InventoryContext db = new InventoryContext(); TestItemInventoryVM vm = new TestItemInventoryVM(); var regularlyOrderedProducts = (from p in db.Products where p.TestId == testId && p.RegularlyOrdered == true select p).ToList(); var invItems = (from i in db.InventoryItems where i.Product.TestId == testId && i.InventoryId == inventoryId select i).ToList(); foreach (var item in regularlyOrderedProducts) { TestItemInventoryVM.Product p = new TestItemInventoryVM.Product { Id = item.Id, Name = item.Name, MaxInStock = item.MaxInStock, UnitsInStock = item.UnitsInStock, }; var invItem = (from i in invItems where i.ProductId == p.Id select i).FirstOrDefault(); if (invItem != null) { p.IsInventoried = invItem.IsInventoried; } vm.RegularlyOrderedProducts.Add(p); } vm.InventoryId = inventoryId; vm.Test = db.Tests.Find(testId); Inventory inventory = db.Inventories.Find(inventoryId); return View(vm); }