public async Task <IActionResult> AddBook([FromBody] BookForAdminViewModel model) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var check = await _context.Authors.AnyAsync(); Author author = null; if (check) { var checkBook = await _context.Books .FirstOrDefaultAsync(b => b.Name == model.Name && b.Author.Name == model.AuthorName); if (checkBook != null) { return(BadRequest("There is already book with the same name and author")); } author = await _context.Authors .FirstOrDefaultAsync(a => a.Name == model.AuthorName); } if (author == null) { author = new Author { Name = model.AuthorName }; author = (_context.Authors.Add(author)).Entity; } var book = _mapper.Map <Book>(model); _context.Books.Add(book); await _context.SaveChangesAsync(); book = await _context.Books.Include(b => b.Author).FirstAsync(b => b.Name == book.Name && b.Author.Name == model.AuthorName); return(Ok(_mapper.Map <BookForAdminViewModel>(book))); }
public async Task <IActionResult> UpdateBook(int id, [FromBody] BookForAdminViewModel model) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var book = await _context.Books.Include(b => b.Author) .FirstOrDefaultAsync(b => b.Id == id); if (book == null) { return(BadRequest($"There is no book with id : {id} in database")); } var author = book.Author; book.Name = model.Name; book.Price = model.Price; book.IsVisibleInCatalog = model.IsVisible; book.CommentsActive = model.CommentsActive; book.AmInStock = model.AmInStock.Value; if (model.AuthorName != author.Name) { author = await _context.Authors .FirstOrDefaultAsync(a => a.Name == model.AuthorName); book.Author = author ?? _context.Authors.Add(new Author { Name = model.AuthorName }).Entity; } _context.Books.Update(book); await _context.SaveChangesAsync(); return(Ok(_mapper.Map <BookForAdminViewModel>(book))); }