//// //// GET: /DistributedBook/Create //public ActionResult Create(int EventID) //{ // ViewBag.BookID = new SelectList(db.BookMasters.OrderBy(o=>o.BookName), "BookID", "BookName"); // ViewBag.EventID = new SelectList(db.InboundMasters.Where(o => o.InboundMasterID == InboundMasterID), "InboundMasterID", "EventDescription"); // return View(new DistributedBook { EventMaster = db.InboundMasters.Where(o => o.InboundMasterID == InboundMasterID).SingleOrDefault(), InboundMasterID = InboundMasterID }); //} //// //// POST: /DistributedBook/Create //[HttpPost] //public ActionResult Create(DistributedBook distributedbook) //{ // if (ModelState.IsValid) // { // AddDistributedBook(distributedbook); // db.SaveChanges(); // return RedirectToAction("Index", new { distributedbook.InboundMasterID }); // } // ViewBag.BookID = new SelectList(db.BookMasters, "BookID", "BookName", distributedbook.BookID); // ViewBag.EventID = new SelectList(db.InboundMasters, "EventID", "EventDescription", distributedbook.InboundMasterID); // return View(distributedbook); //} private void AddDistributedBook(InboundBook distributedbook) { var matchedItem = db.InboundBooks.Where(o => o.InboundMasterID == distributedbook.InboundMasterID && o.BookID == distributedbook.BookID); if (matchedItem.Count() > 1) { throw new Exception("Invalid Data"); } else if (matchedItem.Count() == 1) { var item = matchedItem.SingleOrDefault(); item.NumberOfBooks = item.NumberOfBooks + distributedbook.NumberOfBooks; db.Entry(item).State = EntityState.Modified; } else { db.InboundBooks.Add(distributedbook); } }
public ActionResult Edit(InboundBook distributedbook) { if (ModelState.IsValid) { var matchedItem = db.InboundBooks.Where(o => o.InboundMasterID == distributedbook.InboundMasterID && o.BookID == distributedbook.BookID); if (matchedItem.Count() ==0)//added a new book { db.Entry(distributedbook).State = EntityState.Modified; } else if (matchedItem.Count() > 1) { throw new Exception("Invalid Data"); } else if (matchedItem.Count() == 1 && matchedItem.SingleOrDefault().InboundBookID != distributedbook.InboundBookID)//modifed but books already existing { var item = matchedItem.SingleOrDefault(); item.NumberOfBooks = item.NumberOfBooks + distributedbook.NumberOfBooks; db.Entry(item).State = EntityState.Modified; var removedbook = db.InboundBooks.Find(distributedbook.InboundBookID); db.InboundBooks.Remove(removedbook); } else//modified the same book { matchedItem.SingleOrDefault().NumberOfBooks = distributedbook.NumberOfBooks; //db.Entry(distributedbook).State = EntityState.Modified; } db.SaveChanges(); return RedirectToAction("Index", new { distributedbook.InboundMasterID }); } ViewBag.BookID = new SelectList(db.BookMasters, "BookID", "BookName", distributedbook.BookID); ViewBag.InboundMasterID = new SelectList(db.InboundMasters, "InboundMasterID", "Description", distributedbook.InboundMasterID); return View(distributedbook); }