public IActionResult CreateBookForAuthor(Guid authorId, [FromBody] CreateBookDto createBookDto) { if (createBookDto == null) { return(BadRequest()); } if (string.Equals(createBookDto.Title, createBookDto.Description)) { ModelState.AddModelError(nameof(CreateBookDto), "The title cannot be the same as the description"); } if (!ModelState.IsValid) { return(new UnprocessableEntityObjectResult(ModelState)); } if (!_libraryRepository.AuthorExists(authorId)) { return(NotFound()); } var book = createBookDto.ToBook(authorId); _libraryRepository.AddBookForAuthor(authorId, book); _libraryRepository.Save(); var bookDto = new BookDto(book); bookDto = CreateLinksForBook(bookDto); return(CreatedAtRoute(nameof(GetBookForAuthor), new { authorId, id = book.Id }, bookDto)); }
private static async Task <BookDto> CreateBook(CreateBookDto createBookDto, IRepository <Book> bookRepository) { Book book = createBookDto.ToBook(); Book?createdBook = await bookRepository.CreateAsync(book); return(createdBook.ToBookDto()); }
public async Task <BookDto> CreateBookAsync(CreateBookDto createBookDto) { var book = await _repository.Books .AsNoTracking() .FirstOrDefaultAsync(b => b.Title.Equals(createBookDto.Title)); if (!(book is null)) { throw new EntityAlreadyExistsException("Title duplication"); } var newBook = createBookDto.ToBook(); await _repository.Books.AddAsync(newBook); await _repository.SaveChangesAsync(); return(newBook.AdaptToDto()); }