public async Task <ActionResult <Book> > PostBook([FromForm] BooksBDL book) { Book bookDetails = new Book(); var authorlist = await _context.Authors.ToListAsync(); var booklist = await _context.Books.ToListAsync(); if (book == null) { return(NotFound()); } foreach (var books in booklist) { if (books.Abbrv == book.Abbrv) { return(Conflict("Book already exists")); } } bool alreadyexist = authorlist.Any(aId => aId.AuthorId == book.AuthorId); if (alreadyexist) { bookDetails.AuthorId = book.AuthorId; bookDetails.Abbrv = book.Abbrv; bookDetails.BookTitle = book.BookTitle; bookDetails.TotalPages = book.TotalPages; bookDetails.BookId = book.BookId; } else { return(Conflict("Author not exists")); } _context.Books.Add(bookDetails); try { await _context.SaveChangesAsync(); } catch (DbUpdateException) { if (BookExists(book.BookId)) { return(Conflict("Book already exists")); } else { throw; } } return(CreatedAtAction("BookCreated", new { message = "Book details created with Book ID : " + bookDetails.BookId, id = bookDetails.BookId })); }
public async Task <IActionResult> PutBook(int id, [FromForm] BooksBDL book) { var bookDetails = await _context.Books.FindAsync(id); var authorlist = await _context.Authors.ToListAsync(); var booklist = await _context.Books.ToListAsync(); if (bookDetails == null) { return(BadRequest(new { message = "Book not found" })); } if (id != book.BookId) { return(BadRequest(new { message = "Book ID is incorrect" })); } foreach (var books in booklist) { if (books.Abbrv == book.Abbrv) { return(Conflict("Book already exists")); } } if (book.AuthorId != null) { bool author = authorlist.Any(aId => aId.AuthorId == book.AuthorId); if (author) { bookDetails.AuthorId = book.AuthorId; } else { return(Conflict("Author not exists")); } } if (book.Abbrv != null && book.BookTitle != null) { bookDetails.Abbrv = book.Abbrv; } bookDetails.BookTitle = book.BookTitle; if (book.Isbn != null) { bookDetails.Isbn = book.Isbn; } if (book.BookId != 0) { bookDetails.BookId = book.BookId; } if (book.TotalPages != 0) { bookDetails.TotalPages = book.TotalPages; } _context.Entry(bookDetails).State = EntityState.Modified; try { await _context.SaveChangesAsync(); return(Ok(new { message = "Book details updated Successfully." })); } catch (DbUpdateConcurrencyException) { if (!BookExists(id)) { return(NotFound()); } else { throw; } } }