public ActionResult Edit(DistributedBook distributedbook)
 {
     if (ModelState.IsValid)
     {
         var matchedItem = db.DistributedBooks.Where(o => o.EventID == distributedbook.EventID && 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().DistributedBookID != distributedbook.DistributedBookID)//modifed but books already existing
         {
             var item = matchedItem.SingleOrDefault();
             item.NumberOfBooks = item.NumberOfBooks + distributedbook.NumberOfBooks;
             db.Entry(item).State = EntityState.Modified;
             var removedbook= db.DistributedBooks.Find(distributedbook.DistributedBookID);
             db.DistributedBooks.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.EventID });
     }
     ViewBag.BookID = new SelectList(db.BookMasters, "BookID", "BookName", distributedbook.BookID);
     ViewBag.EventID = new SelectList(db.EventMasters, "EventID", "EventDescription", distributedbook.EventID);
     return View(distributedbook);
 }
        private void AddDistributedBook(DistributedBook distributedbook)
        {
            var matchedItem = db.DistributedBooks.Where(o => o.EventID == distributedbook.EventID && 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.DistributedBooks.Add(distributedbook);
            }
        }
        public ActionResult Create(DistributedBook distributedbook)
        {
            if (ModelState.IsValid)
            {
                AddDistributedBook(distributedbook);
                db.SaveChanges();
                return RedirectToAction("Index", new { distributedbook.EventID });
            }

            ViewBag.BookID = new SelectList(db.BookMasters, "BookID", "BookName", distributedbook.BookID);
            ViewBag.EventID = new SelectList(db.EventMasters, "EventID", "EventDescription", distributedbook.EventID);
            return View(distributedbook);
        }