public static void GiveBookToUser(BooksDataContext db, string bookArg, string authorArg) { int userId; if (!int.TryParse(authorArg, out userId)) { Console.WriteLine("Invalid user ID! Operation aborted!"); return; } int bookId; if (!int.TryParse(bookArg, out bookId)) { Console.WriteLine("Invalid book ID! Operation aborted!"); return; } var userToLendTo = (from user in db.Users where user.UserID == userId select user).SingleOrDefault(); if (userToLendTo == null) { Console.WriteLine("No such user! Operation aborted!"); return; } var bookToLend = (from book in db.Books where book.BookID == bookId select book).SingleOrDefault(); if (bookToLend == null) { Console.WriteLine("No such book! Operation aborted!"); return; } var userLoanings = from loanedBook in db.LoanedBooks where loanedBook.UserID == userId select loanedBook.Quantity; int loanedBooksByUser = userLoanings.Any() ? userLoanings.Sum() : 0; if (loanedBooksByUser == 5) { Console.WriteLine("User can't lend more than 5 books! Operation aborted!"); return; } var bookQuantities = (from book in db.LoanedBooks where book.BookID == bookId select book.Quantity); int givenCopies = bookQuantities.Any() ? bookQuantities.Sum() : 0; var availableCopies = bookToLend.Quantity - givenCopies; if (availableCopies == 0) { Console.WriteLine("No more available copies of the book! Operation aborted!"); return; } var bookLoan = (from loanedBook in db.LoanedBooks where loanedBook.BookID == bookId && loanedBook.UserID == userId select loanedBook).SingleOrDefault(); if (bookLoan == null) { var newBookLoan = new LoanedBook(); newBookLoan.BookID = bookId; newBookLoan.UserID = userId; newBookLoan.Quantity = 1; newBookLoan.LoanDate = DateTime.Now; newBookLoan.ExpirationDate = DateTime.Now.AddMonths(1); db.LoanedBooks.InsertOnSubmit(newBookLoan); } else { bookLoan.Quantity++; bookLoan.LoanDate = DateTime.Now; bookLoan.ExpirationDate = DateTime.Now.AddMonths(1); } try { db.SubmitChanges(); } catch (ChangeConflictException ex) { Console.WriteLine("Cannot update info in database! Operation exited with message:"); Console.WriteLine(ex.Message); return; } Console.WriteLine("Book loaned successfully!"); }