Esempio n. 1
0
        public ActionResult Create(BorrowCreateViewModel model)
        {
            if (model.ChoosenBooks.Contains(-1))
            {
                ModelState.AddModelError("emptyBook", "Each list must have a book selected");
            }
            if (model.ChoosenBooks.Length != model.ChoosenBooks.Distinct().Count())
            {
                ModelState.AddModelError("haveDuplicate", "It isn't possible to borrow two identical books.");
            }
            if (!ModelState.IsValid)
            {
                var errorList = (from item in ModelState
                                 where item.Value.Errors.Any()
                                 select item.Value.Errors[0].ErrorMessage).ToList();
                return(Json(new { success = false, errors = errorList }, JsonRequestBehavior.AllowGet));
            }

            borrowService.InsertBorrows(model);
            return(Json(new { success = true }, JsonRequestBehavior.AllowGet));
        }
Esempio n. 2
0
        public void InsertBorrows(BorrowCreateViewModel model)
        {
            var newBorrows = new List <Borrow>();

            foreach (var book in model.ChoosenBooks)
            {
                newBorrows.Add(new Borrow
                {
                    UserId     = model.UserId,
                    BookId     = book,
                    FromDate   = DateTime.Now,
                    ToDate     = model.ToDate,
                    IsReturned = false
                });
            }
            libraryEntities.Borrows.AddRange(newBorrows);
            libraryEntities.SaveChanges();

            var books = libraryEntities.Books.Where(x => model.ChoosenBooks.Contains(x.BookId)).ToList();

            books.ForEach(x => x.Count = x.Count - 1);
            libraryEntities.SaveChanges();
        }