public ActionResult PartiallyUpdateBookForAuthor(Guid authorid, Guid id, JsonPatchDocument <BookforUpdateDto> docPatch) { if (docPatch == null) { return(BadRequest()); } if (!_libraryRepository.AuthorExists(authorid)) { return(NotFound()); } //Find The Book by Author and BookId var BookforAuthorFromRepo = _libraryRepository.GetBookForAuthor(authorid, id); if (BookforAuthorFromRepo == null) { var BookforUpdateDto = new BookforUpdateDto(); docPatch.ApplyTo(BookforUpdateDto); var book = Mapper.Map <Book>(BookforUpdateDto); book.Id = id; _libraryRepository.AddBookForAuthor(authorid, book); if (!_libraryRepository.Save()) { throw new Exception($"Error Creating the Book for {authorid}"); } return(CreatedAtRoute("GetBookByAuthor", new { authorid = authorid, bookId = id }, book)); } //Convert the Book to BookforUpdateDto so JsonPatch can be applied var booktoPatch = Mapper.Map <BookforUpdateDto>(BookforAuthorFromRepo); //Apply The Patch //docPatch.ApplyTo(booktoPatch, ModelState); docPatch.ApplyTo(booktoPatch); if (!ModelState.IsValid) { return(new UnprocessableEntityObjectResult(ModelState)); } //Tranfer the Update booktoPatch to Book Mapper.Map(booktoPatch, BookforAuthorFromRepo); //Add the Patched Book to Repo _libraryRepository.UpdateBookForAuthor(BookforAuthorFromRepo); if (!_libraryRepository.Save()) { throw new Exception("Error while Patch the Book"); } return(NoContent()); }
public ActionResult UpdateBookforAuthor(Guid authorid, Guid id, [FromBody] BookforUpdateDto book) { if (book == null) { return(BadRequest()); } if (!_libraryRepository.AuthorExists(authorid)) { return(NotFound()); } var bookforUpdatefromRepo = _libraryRepository.GetBookForAuthor(authorid, id); if (bookforUpdatefromRepo == null) { var booktoAdd = Mapper.Map <Book>(book); if (booktoAdd != null) { booktoAdd.Id = id; } _libraryRepository.AddBookForAuthor(authorid, booktoAdd); if (_libraryRepository.Save()) { return(CreatedAtRoute("GetBookByAuthor", new { authorid = authorid, bookId = id }, booktoAdd)); } } Mapper.Map(book, bookforUpdatefromRepo); _libraryRepository.UpdateBookForAuthor(bookforUpdatefromRepo); if (!_libraryRepository.Save()) { throw new Exception("Error while updating the Book"); } return(NoContent()); }