public async Task <ActionResult <BookDto> > CreateBookForAuthorAsync(Guid authorId, [FromBody] BookForCreationDto book) { if (book == null) { return(BadRequest()); } // As the [ApiController] attribute, the common validation is handled by it, such as model binding. // So only custom validation is handled by this code if (book.Description == book.Title) { ModelState.AddModelError(nameof(BookForCreationDto), "The provided description should be different from the title."); } if (!ModelState.IsValid) { // return 422 return(new UnprocessableEntityObjectResult(ModelState)); } if (!await _libraryRepository.AuthorExistsAsync(authorId)) { return(NotFound()); } var bookEntity = _mapper.Map <Book>(book); await _libraryRepository.AddBookForAuthorAsync(authorId, bookEntity); if (!await _libraryRepository.SaveChangesAsync()) { throw new Exception($"Creating a book for author {authorId} failed on save."); } var bookToReturn = _mapper.Map <BookDto>(bookEntity); return(CreatedAtRoute( "GetBookForAuthor", new { authorId = authorId, bookId = bookToReturn.Id }, CreateLinksForBook(bookToReturn))); }