コード例 #1
0
        public async Task <bool> UpdateBook(BookForUpdateDto bookForUpdate, Guid bookId)
        {
            var book   = _mapper.Map <Book>(bookForUpdate);
            var result = await _bookRepository.UpdateBook(book, bookId);

            return(result);
        }
コード例 #2
0
        public IActionResult ParticallyUpdateBook(Guid authorId, Guid bookId, JsonPatchDocument <BookForUpdateDto> patchDocument)
        {
            if (!AuthorRepository.IsAuthorExists(authorId))
            {
                return(NotFound());
            }

            var book = BookRepository.GetBookForAuthor(authorId, bookId);

            if (book == null)
            {
                return(NotFound());
            }

            var bookToPatch = new BookForUpdateDto
            {
                Title       = book.Title,
                Description = book.Description,
                Pages       = book.Pages
            };

            patchDocument.ApplyTo(bookToPatch);
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            BookRepository.UpdateBook(authorId, bookId, bookToPatch);
            return(NoContent());
        }
コード例 #3
0
        public ActionResult PatchBookForAuthor([FromRoute] string authorId, [FromRoute] string bookId, JsonPatchDocument <BookForUpdateDto> patchDocument)
        {
            if (!_authorService.AuthorExists(authorId))
            {
                return(NotFound());
            }

            if (!_bookService.BookExists(bookId))
            {
                return(NotFound());
            }

            BookDto book = _bookService.GetBooksForAuthor(authorId).Where(b => b.Id == bookId).FirstOrDefault();

            BookForUpdateDto bookForUpdate = new BookForUpdateDto
            {
                AuthorId      = authorId,
                BookId        = bookId,
                Genre         = book.Genre,
                Price         = book.Price,
                PublishedDate = book.PublishedDate,
                Title         = book.Title
            };

            if (!TryValidateModel(bookForUpdate))
            {
                return(ValidationProblem(ModelState));
            }

            patchDocument.ApplyTo(bookForUpdate, ModelState);

            _bookService.UpdateBook(bookForUpdate);

            return(NoContent());
        }
コード例 #4
0
        public IActionResult UpdateBookForAuthor(int authorId, int id, [FromBody] BookForUpdateDto book)
        {
            if (book == null)
            {
                return(BadRequest());
            }

            if (!ModelState.IsValid)
            {
                return(new UnprocessableEntityObjectResult(ModelState));
            }

            if (!_libraryRepository.AuthorExists(authorId))
            {
                return(NotFound());
            }

            var bookForAuthorEntity = _libraryRepository.GetBookForAuthor(authorId, id);

            if (bookForAuthorEntity == null)
            {
                return(NotFound());
            }

            Mapper.Map(book, bookForAuthorEntity);

            if (!_libraryRepository.Save())
            {
                throw new Exception($"Updating book {id} for author {authorId} failed on save.");
            }

            return(NoContent());
        }
コード例 #5
0
        public IActionResult UpdateBookForAuthor(Guid authorId,
            Guid bookId,
            BookForUpdateDto book)
        {
            if (!_restApiRepository.AuthorExists(authorId))
            {
                return NotFound();
            }
            var bookForAuthorFromRepo = _restApiRepository.GetBook(authorId, bookId);
            if (bookForAuthorFromRepo == null)
            {
                var bookToAdd = _mapper.Map<Book>(book);
                bookToAdd.Id = bookId;
                _restApiRepository.AddBook(authorId, bookToAdd);
                _restApiRepository.Save();

                var bookToReturn = _mapper.Map<BookDto>(bookToAdd);
                return CreatedAtRoute("GetBookForAuthor",
                    new { authorId, bookId = bookToReturn.Id },
                    bookToReturn);
            }

            _mapper.Map(book, bookForAuthorFromRepo);
            _restApiRepository.UpdateBook(bookForAuthorFromRepo);
            _restApiRepository.Save();

            return NoContent();
        }
コード例 #6
0
        public IActionResult PartiallyUpdateBook(Guid authorId, Guid bookId, [FromBody] JsonPatchDocument <BookForUpdateDto> patchDocument)
        {
            if (!AuthorRepository.IsAuthorExists(authorId))
            {
                return(NotFound());
            }

            var book = BookRepository.GetBookForAuthor(authorId, bookId);

            if (book == null)
            {
                return(NotFound());
            }

            var bookToPatch = new BookForUpdateDto
            {
                Title       = book.Title,
                Description = book.Description,
                Pages       = book.Pages
            };

            //ApplyTo是将patchDocument中相应的修改操作应用到新建的对象bookToPatch上
            //错误会被记录到到ModelStateDictionary中,通过ModelState.IsValid判断是否有错误,并且在错误时返回bad request 400
            patchDocument.ApplyTo(bookToPatch, ModelState);
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            Console.WriteLine(bookToPatch.Title);
            BookRepository.UpdateBook(authorId, bookId, bookToPatch);
            return(NoContent());
        }
コード例 #7
0
        public IActionResult UpdateBookForAuthor(Guid authorId, Guid id,
                                                 [FromBody] BookForUpdateDto book)
        {
            if (book == null)
            {
                return(BadRequest());
            }

            if (!_libraryRepository.AuthorExists(authorId))
            {
                return(NotFound());
            }

            var bookForAuthorFromRepo = _libraryRepository.GetBookForAuthor(authorId, id);

            if (bookForAuthorFromRepo == null)
            {
                return(NotFound());
            }

            Mapper.Map(book, bookForAuthorFromRepo);

            _libraryRepository.UpdateBookForAuthor(bookForAuthorFromRepo);

            if (!_libraryRepository.Save())
            {
                throw new Exception($"Updating book for author {authorId} failed on save.");
            }

            return(NoContent());
        }
コード例 #8
0
        public IActionResult UpdateBookForAuthor(Guid authorId, Guid bookId, [FromBody] BookForUpdateDto bookDto)
        {
            if (bookDto == null)
            {
                return(BadRequest());
            }

            if (bookDto.Description == bookDto.Title)
            {
                ModelState.AddModelError(nameof(BookForUpdateDto), "The provided description should be different from the title.");
            }

            if (!ModelState.IsValid)
            {
                // return 422;
                return(new UnprocessableEntityObjectResult(ModelState));
            }

            if (!c_libraryRepository.AuthorExists(authorId))
            {
                return(NotFound());
            }

            Book bookEntity = c_libraryRepository.GetBookForAuthor(authorId, bookId);

            if (bookEntity == null)
            {
                var bookToAdd = Mapper.Map <Book>(bookDto);
                bookToAdd.Id = bookId;

                c_libraryRepository.AddBookForAuthor(authorId, bookToAdd);

                if (!c_libraryRepository.Save())
                {
                    throw new Exception($"Upserting book {bookId} for author {authorId} failed when saving.");
                }

                var bookToReturn = Mapper.Map <BookDto>(bookToAdd);

                return(CreatedAtRoute(
                           "GetBookForAuthor",
                           new
                {
                    authorId = authorId,
                    bookId = bookToReturn.Id
                },
                           bookToReturn));
            }

            Mapper.Map(bookDto, bookEntity);

            c_libraryRepository.UpdateBookForAuthor(bookEntity);

            if (!c_libraryRepository.Save())
            {
                throw new Exception($"Failed updating book {bookId} for author {authorId} failed when saving.");
            }

            return(Ok(bookEntity));
        }
コード例 #9
0
        public async Task UpdateBookForAuthorAsync_ThrowException_Test()
        {
            // Arrange
            var authorId         = Guid.Parse("a1da1d8e-1988-4634-b538-a01709477b77");
            var bookId           = Guid.Parse("1325360c-8253-473a-a20f-55c269c20407");
            var bookForUpdateDto = new BookForUpdateDto {
                Title = "A Book Title", Description = "Some Description"
            };
            var book = GetTestAuthorsData().FirstOrDefault(a => a.Id == authorId)
                       .Books.FirstOrDefault(b => b.Id == bookId);
            var mockRepo = new Mock <ILibraryRepository>();

            mockRepo.Setup(repo => repo.AuthorExistsAsync(authorId))
            .Returns(Task.FromResult(true));
            mockRepo.Setup(repo => repo.GetBookForAuthorAsync(authorId, bookId))
            .ReturnsAsync(book);
            mockRepo.Setup(repo => repo.UpdateBookForAuthorAsync(book))
            .Returns(Task.CompletedTask);
            mockRepo.Setup(repo => repo.SaveChangesAsync())
            .ReturnsAsync(false);
            var mapper     = new MapperConfiguration(cfg => cfg.AddProfile(new BookProfile())).CreateMapper();
            var controller = new BooksController(mockRepo.Object, mapper);

            // Act
            var result = await Assert.ThrowsAsync <Exception>(() => controller.UpdateBookForAuthorAsync(authorId, bookId, bookForUpdateDto));

            // Assert
            Assert.Equal($"Update book {bookId} for author {authorId} failed on save.", result.Message);
        }
コード例 #10
0
ファイル: BooksController.cs プロジェクト: alstan/Library
        public IActionResult UpdateBookForAuthor(Guid authorId, Guid id, [FromBody] BookForUpdateDto book)
        {
            if (!_libraryRepository.AuthorExists(authorId))
            {
                return(NotFound());
            }

            var bookForAuthor = _libraryRepository.GetBookForAuthor(authorId, id);

            if (bookForAuthor == null)
            {
                var bookToAdd = Mapper.Map <Book>(book);
                bookToAdd.Id = id;
                _libraryRepository.AddBookForAuthor(authorId, bookToAdd);

                if (!_libraryRepository.Save())
                {
                    throw new Exception();
                }

                var bookResult = Mapper.Map <BookDto>(bookToAdd);
                return(CreatedAtRoute("GetBook", new { authorId, id = bookResult.Id }, bookResult));
            }

            Mapper.Map(book, bookForAuthor);

            _libraryRepository.UpdateBookForAuthor(bookForAuthor);

            if (!_libraryRepository.Save())
            {
                throw new Exception();
            }

            return(NoContent());
        }
コード例 #11
0
        public IActionResult UpdateBookForAuthor(Guid authorId, Guid bookId, BookForUpdateDto bookForUpdateDto)
        {
            if (!_bookLibraryRepository.AuthorExists(authorId))
            {
                return(NotFound());
            }

            var bookFromRepo = _bookLibraryRepository.GetBook(authorId, bookId);

            if (bookFromRepo == null)
            {
                var bookEntity = _mapper.Map <Book>(bookForUpdateDto);
                bookEntity.Id = bookId;
                _bookLibraryRepository.AddBook(authorId, bookEntity);
                _bookLibraryRepository.Save();


                var bookToReturn = _mapper.Map <BookDto>(bookEntity);
                return(CreatedAtRoute("GetBookForAuthor", new { authorId, bookId = bookToReturn.Id },
                                      bookToReturn));
            }

            _mapper.Map(bookForUpdateDto, bookFromRepo);
            _bookLibraryRepository.UpdateBook(bookFromRepo);
            _bookLibraryRepository.Save();

            return(NoContent());
        }
コード例 #12
0
        public async Task BadRequestUpdateABookTest()
        {
            BookForUpdateDto book = new BookForUpdateDto()
            {
                //Title = SeedData.book1.Title,
                //Description = "Test Description",
                Publisher = SeedData.book1.Publisher,
                ISBN      = SeedData.book1.ISBN,
                Genres    = SeedData.book1.Genres.Select(g => g.Name).ToList(),
                Language  = SeedData.book1.Language,
                Authors   = new List <AuthorForCreationDto>()
                {
                    new AuthorForCreationDto()
                    {
                        FirstName   = SeedData.author1.FirstName,
                        LastName    = SeedData.author1.LastName,
                        DateOfBirth = SeedData.author1.DateOfBirth
                    }
                }
            };

            var json          = JsonConvert.SerializeObject(book);
            var stringContent = new StringContent(json, UnicodeEncoding.UTF8, "application/json");

            _client.DefaultRequestHeaders.Authorization =
                new AuthenticationHeaderValue("Bearer", await GetJwtAsync());

            string bookId   = SeedData.book1.BookId.ToString();
            var    response = await _client.PutAsync($"/api/books/{bookId}", stringContent);

            //response.EnsureSuccessStatusCode();

            Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
        }
コード例 #13
0
        public IActionResult UpdateBook(int userId, int id,
                                        [FromBody] BookForUpdateDto book)
        {
            if (book == null)
            {
                return(BadRequest());
            }

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (!_bookTradeRepository.UserExists(userId))
            {
                return(NotFound());
            }

            var bookEntity = _bookTradeRepository.GetBookOfUser(userId, id);

            if (bookEntity == null)
            {
                return(NotFound());
            }

            Mapper.Map(book, bookEntity);

            if (!_bookTradeRepository.Save())
            {
                return(StatusCode(500, "A problem happened while handling your request."));
            }

            return(NoContent());
        }
コード例 #14
0
        public async Task <IActionResult> UpdateBook(int id, [FromBody] BookForUpdateDto bookForUpdateDto)
        {
            var location = GetControllerActionNames();

            try
            {
                _logger.LogInfo($" {location}: Update Book");
                if (id < 1 || bookForUpdateDto == null || id != bookForUpdateDto.Id)
                {
                    _logger.LogWarn($" {location}: Empty Request was submitted");
                    return(BadRequest(ModelState));
                }
                if (!ModelState.IsValid)
                {
                    _logger.LogWarn($" {location}: Data was incomplete");
                    return(BadRequest(ModelState));
                }
                if (!await _bookRepository.isExist(id))
                {
                    _logger.LogWarn($" {location}: Book does not exist");
                    return(NotFound($" {location}: Book does not exist"));
                }
                var book      = _mapper.Map <Book>(bookForUpdateDto);
                var IsSuccess = await _bookRepository.Update(book);

                if (!IsSuccess)
                {
                    return(InternalError($" {location}: Update Failed for Record Id: {id}"));
                }
                return(NoContent());
            } catch (Exception _ex)
            {
                return(InternalError($"{_ex.Message}\n{_ex.InnerException}"));
            }
        }
コード例 #15
0
        public IActionResult UpdateBookForAuthor(Guid authorId, Guid id,
                                                 [FromBody] BookForUpdateDto book)
        {
            if (book == null)
            {
                return(BadRequest());
            }

            if (book.Description == book.Title)
            {
                ModelState.AddModelError(nameof(BookForUpdateDto),
                                         "The provided description should be different from the title.");
            }

            if (!ModelState.IsValid)
            {
                return(new UnprocessableEntityObjectResult(ModelState));
            }

            if (!_libraryRepository.AuthorExists(authorId))
            {
                return(NotFound());
            }

            var bookForAuthorFromRepo = _libraryRepository.GetBookForAuthor(authorId, id);

            if (bookForAuthorFromRepo == null)
            {
                var bookToAdd = Mapper.Map <Book>(book);
                bookToAdd.Id = id;

                _libraryRepository.AddBookForAuthor(authorId, bookToAdd);

                if (!_libraryRepository.Save())
                {
                    throw new Exception($"Upserting book {id} for author {authorId} failed on save.");
                }

                var bookToReturn = Mapper.Map <BookDto>(bookToAdd);

                return(CreatedAtRoute("GetBookForAuthor",
                                      new { authorId = authorId, id = bookToReturn.Id },
                                      bookToReturn));
            }

            // 1. Map the entity to a BookForUpdateDto
            // 2. Apply the updated field values to that DTO
            // 3. Map the BookForUpdateDto back to entity
            Mapper.Map(book, bookForAuthorFromRepo);

            _libraryRepository.UpdateBookForAuthor(bookForAuthorFromRepo);

            if (!_libraryRepository.Save())
            {
                throw new Exception($"Updating book {id} for author {authorId} failed on save.");
            }

            return(NoContent());
        }
コード例 #16
0
        public IActionResult UpdateBookForAuthor(Guid authorId, Guid id,
                                                 [FromBody] BookForUpdateDto book)
        {
            if (book == null)
            {
                return(BadRequest());
            }

            if (book.Title == book.Description)
            {
                ModelState.AddModelError(nameof(BookForUpdateDto),
                                         "Title and descriptiom have to be different");
            }
            if (!ModelState.IsValid)
            {
                return(new UnprocesableEntityObjectResult(ModelState));
            }

            if (!_libraryRepository.AuthorExists(authorId))
            {
                return(NotFound());
            }
            var bookForAuthorFromRepo = _libraryRepository.GetBookForAuthor(authorId, id);

            if (bookForAuthorFromRepo == null)
            {
                //   return NotFound("Book For Author not found");
                #region "Upserting"
                var bookToAdd = AutoMapper.Mapper.Map <Book>(book);
                bookToAdd.Id = id;
                _libraryRepository.AddBookForAuthor(authorId, bookToAdd);

                if (!_libraryRepository.Save())
                {
                    throw new Exception($"Upserting  book {id} for author {authorId} failed on save");
                }
                var bookToReturn = AutoMapper.Mapper.Map <BookDto>(bookToAdd);
                return(CreatedAtRoute("GetBookForAuthor",
                                      new { authorId, id = bookToReturn.Id }, bookToReturn));

                #endregion
            }


            //we need to copy values from [FromBody] book to the book record in DB represented by bookForAuthorFromRepo
            AutoMapper.Mapper.Map(book, bookForAuthorFromRepo);

            //UpdateBookForAuthor is an empyty method and does nothing,
            //bcoz in EF Core entities are tracked by Context. We call Maper.map(source, destn)
            //which copies new values from dto into actual entity
            //then we call repository.save() which sends changes to DB so below method can be skipped
            _libraryRepository.UpdateBookForAuthor(bookForAuthorFromRepo);

            if (!_libraryRepository.Save())
            {
                throw new Exception($"Updating boook {id} for author {authorId} failed on save");
            }
            return(NoContent());
        }
コード例 #17
0
        public IActionResult UpdateBookForAuthor(Guid authorId, Guid id, [FromBody] BookForUpdateDto book)
        {
            if (book == null)
            {
                return(this.BadRequest());
            }

            if (book.Title == book.Description)
            {
                this.ModelState.AddModelError(nameof(BookForUpdateDto), "The provided description should be different from the title.");
            }

            if (!this.ModelState.IsValid)
            {
                // return 422 - Unprocessable Entity
                return(new UnprocessableEntityObjectResult(this.ModelState));
            }
            else if (!this.libraryRepository.AuthorExists(authorId))
            {
                return(this.NotFound());
            }
            else
            {
                var bookForAuthorFromRepo = this.libraryRepository.GetBookForAuthor(authorId, id);

                if (bookForAuthorFromRepo == null)
                {
                    var bookToAdd = Mapper.Map <Book>(book);
                    bookToAdd.Id = id;

                    this.libraryRepository.AddBookForAuthor(authorId, bookToAdd);

                    if (!this.libraryRepository.Save())
                    {
                        throw new LibraryException($"Upserting book {id} for author {authorId} failed on save.");
                    }
                    else
                    {
                        var bookToReturn = Mapper.Map <BookDto>(bookToAdd);
                        return(this.CreatedAtRoute(nameof(GetBookForAuthor), new { authorId, id = bookToReturn.Id }, bookToReturn));
                    }
                }
                else
                {
                    Mapper.Map(book, bookForAuthorFromRepo);
                    this.libraryRepository.UpdateBookForAuthor(bookForAuthorFromRepo);

                    if (!this.libraryRepository.Save())
                    {
                        throw new LibraryException($"Updating book {id} for author {authorId} failed on save.");
                    }
                    else
                    {
                        // Its up to us to either return 204-No Content or 200-OK status
                        return(this.NoContent());
                    }
                }
            }
        }
コード例 #18
0
        public IActionResult PartiallyUpdateBookForAuthor(Guid authorId, Guid id, [FromBody] JsonPatchDocument <BookForUpdateDto> patchDoc)
        {
            if (patchDoc == null)
            {
                return(BadRequest());
            }

            if (!_libraryRepository.AuthorExists(authorId))
            {
                return(NotFound());
            }

            var bookForAuthorFromRepository = _libraryRepository.GetBookForAuthor(authorId, id);

            if (bookForAuthorFromRepository == null)
            {
                BookForUpdateDto bookDto = new BookForUpdateDto();
                patchDoc.ApplyTo(bookDto, ModelState);

                TryValidateModel(bookDto);

                if (!ModelState.IsValid)
                {
                    return(new UnprocessableEntityObjectResult(ModelState));
                }

                var bookToAdd = Mapper.Map <Book>(bookDto);
                bookToAdd.Id = id;

                _libraryRepository.AddBookForAuthor(authorId, bookToAdd);
                if (!_libraryRepository.Save())
                {
                    return(new UnprocessableEntityObjectResult(ModelState));
                }
                var bookToReturn = Mapper.Map <BookDto>(bookToAdd);
                return(CreatedAtRoute("GetBookForAuthor", new { authorId = authorId, id = bookToReturn.Id }, bookToReturn));
            }

            BookForUpdateDto bookToPatch = Mapper.Map <BookForUpdateDto>(bookForAuthorFromRepository);

            patchDoc.ApplyTo(bookToPatch, ModelState);

            TryValidateModel(bookToPatch);

            if (!ModelState.IsValid)
            {
                return(new UnprocessableEntityObjectResult(ModelState));
            }

            Mapper.Map(bookToPatch, bookForAuthorFromRepository);
            _libraryRepository.UpdateBookForAuthor(bookForAuthorFromRepository);

            if (!_libraryRepository.Save())
            {
                throw new Exception($"Patching book {id} for author {authorId} failed on save.");
            }

            return(NoContent());
        }
コード例 #19
0
        public void UpdateBook(Guid authorId, Guid bookId, BookForUpdateDto book)
        {
            var originalBook = GetBookForAuthor(authorId, bookId);

            originalBook.Title       = book.Title;
            originalBook.Description = book.Description;
            originalBook.Pages       = book.Pages;
        }
コード例 #20
0
 public static Book Map(this BookForUpdateDto book)
 {
     return(new Book
     {
         Title = book.Title,
         Description = book.Description
     });
 }
コード例 #21
0
        public IActionResult UpdateBookForAuthor(Guid authorId, Guid id, [FromBody] BookForUpdateDto book)
        {
            if (book == null)
            {
                return(BadRequest());
            }

            if (book.Description == book.Title)
            {
                ModelState.AddModelError(nameof(BookForUpdateDto), "The provided description should be different from the title.");
            }

            if (!ModelState.IsValid)
            {
                return(new UnprocessableEntityObjectResult(ModelState));
            }

            if (!_libraryRepository.AuthorExists(authorId))
            {
                return(NotFound());
            }

            var bookForAuthorFromRepo = _libraryRepository.GetBookForAuthor(authorId, id);

            if (bookForAuthorFromRepo == null)
            {
                // upserting
                var bookToAdd = Mapper.Map <Book>(book);
                bookToAdd.Id = id;

                _libraryRepository.AddBookForAuthor(authorId, bookToAdd);

                if (!_libraryRepository.Save())
                {
                    throw new Exception($"Upserting book {id} for author {authorId} failed on save.");
                }

                var bookToReturn = Mapper.Map <BookDto>(bookToAdd);

                return(CreatedAtRoute("GetBookForAuthor", new { id = bookToReturn.Id, authorId = authorId }, bookToReturn));
            }

            // here the bookFAFR is mapped to an updateDTO, update that DTO from the FromBodyDTO,
            // and map the updated DTO back to Book type
            // bookFAFR changed by the Map call, its tracked by EF
            Mapper.Map(book, bookForAuthorFromRepo);

            // empty impl.
            _libraryRepository.UpdateBookForAuthor(bookForAuthorFromRepo);

            if (!_libraryRepository.Save())
            {
                throw new Exception($"Updating book {id} for author {authorId} failed on save.");
            }

            return(NoContent());
            // or retur Ok();
        }
コード例 #22
0
        public IActionResult UpdateBookForAuthor(Guid authorId, Guid id, [FromBody] BookForUpdateDto book)
        {
            if (book == null)
            {
                return(BadRequest());
            }

            if (book.Description == book.Title)
            {
                ModelState.AddModelError(nameof(BookForUpdateDto), "The provided description should be different from the title.");
            }

            if (!ModelState.IsValid)
            {
                // return 422
                return(new Helpers.UnprocessableEntityObjectResult(ModelState));
            }

            if (!libraryRepository.AuthorExists(authorId))
            {
                return(BadRequest());
            }

            if (!libraryRepository.AuthorExists(authorId))
            {
                return(NotFound());
            }

            Book bookForAuthorFromRepo = libraryRepository.GetBookForAuthor(authorId, id);

            if (bookForAuthorFromRepo == null)
            {
                Book bookToAdd = mapper.Map <Book>(book);
                bookToAdd.Id = id;

                libraryRepository.AddBookForAuthor(authorId, bookToAdd);

                if (!libraryRepository.Save())
                {
                    throw new Exception($"Upserting book {id} for author {authorId} failed on save.");
                }

                BookDto bookToReturn = mapper.Map <BookDto>(bookToAdd);
                return(CreatedAtRoute("GetBookForAuthor", new { authorId, id = bookToReturn.Id }, bookToReturn));
            }

            mapper.Map(book, bookForAuthorFromRepo);

            libraryRepository.UpdateBookForAuthor(bookForAuthorFromRepo);

            if (!libraryRepository.Save())
            {
                throw new Exception($"Updating book {id} for author {authorId} failed on save.");
            }

            return(NoContent());
        }
コード例 #23
0
ファイル: BooksController.cs プロジェクト: Kannan2020/Library
        public IActionResult PartialyUpdateBookForAuthor(Guid authorId, Guid id, [FromBody] JsonPatchDocument <BookForUpdateDto> patchDocument)
        {
            if (patchDocument == null)
            {
                return(BadRequest());
            }
            if (!libraryRepository.AuthorExists(authorId))
            {
                return(NotFound());
            }
            var bookForAuthorFromRepo = libraryRepository.GetBookForAuthor(authorId, id);

            if (bookForAuthorFromRepo == null)
            {
                var bookDto = new BookForUpdateDto();
                // patchDocument.ApplyTo(bookDto, ModelState);
                patchDocument.ApplyTo(bookDto);

                if (string.Equals(bookDto.Title, bookDto.Description, StringComparison.InvariantCultureIgnoreCase))
                {
                    ModelState.AddModelError(nameof(CreateBookDto), "The provider description should be different from the title");
                }
                TryValidateModel(bookDto);
                if (!ModelState.IsValid)
                {
                    return(new Helpers.UnprocessableEntityObjectResult(ModelState));
                }
                var bookToAdd = Mapper.Map <Book>(bookDto);
                bookToAdd.Id = id;
                libraryRepository.AddBookForAuthor(authorId, bookToAdd);
                if (!libraryRepository.Save())
                {
                    throw new Exception($"Update a book {id} for author {authorId} faild on save");
                }
                var bookToReturn = Mapper.Map <BookDto>(bookToAdd);
                return(CreatedAtRoute("GetBookForAuthor", new { authorId, id = bookToReturn.Id }, bookToReturn));
            }
            var bookToPatch = Mapper.Map <BookForUpdateDto>(bookForAuthorFromRepo);

            patchDocument.ApplyTo(bookToPatch, ModelState);
            if (string.Equals(bookToPatch.Title, bookToPatch.Description, StringComparison.InvariantCultureIgnoreCase))
            {
                ModelState.AddModelError(nameof(CreateBookDto), "The provider description should be different from the title");
            }
            TryValidateModel(bookToPatch);
            if (!ModelState.IsValid)
            {
                return(new Helpers.UnprocessableEntityObjectResult(ModelState));
            }
            Mapper.Map(bookToPatch, bookForAuthorFromRepo);
            libraryRepository.UpdateBookForAuthor(bookForAuthorFromRepo);
            if (!libraryRepository.Save())
            {
                throw new Exception($"Update a book for author {authorId} faild on save");
            }
            return(NoContent());
        }
コード例 #24
0
        public async Task <IActionResult> UpdateBook(Guid bookId, BookForUpdateDto book)
        {
            //Book checkBookExists = _repositoryWrapper.Books.Get(bookId);

            //if (checkBookExists == null)
            //{
            //    return NotFound();
            //}

            var bookEntity = await _repositoryWrapper.Books.GetBook(bookId);

            if (!TryValidateModel(bookEntity))
            {
                return(ValidationProblem(ModelState));
            }

            if (bookEntity == null)
            {
                var bookToAdd = _mapper.Map <Book>(book);

                bookToAdd.BookId = bookId;

                _repositoryWrapper.Books.Add(bookToAdd);

                foreach (var author in book.Authors)
                {
                    var authorEntity = _mapper.Map <Author>(author);
                    _repositoryWrapper.Authors.Add(authorEntity);

                    BookAuthor bookAuthor = new BookAuthor()
                    {
                        BookId   = bookToAdd.BookId,
                        Book     = bookToAdd,
                        AuthorId = authorEntity.AuthorId,
                        Author   = authorEntity
                    };

                    _repositoryWrapper.BookAuthors.Add(bookAuthor);
                }

                var bookToReturn = _mapper.Map <BookDto>(bookToAdd);
                return(CreatedAtRoute("GetBook",
                                      new { bookId = bookToReturn.BookId },
                                      bookToReturn));
            }

            _mapper.Map(book, bookEntity);
            _repositoryWrapper.Books.Update(bookEntity);

            foreach (var author in book.Authors)
            {
                var authorEntity = _mapper.Map <Author>(author);
                _repositoryWrapper.Authors.Update(authorEntity);
            }

            return(NoContent());
        }
コード例 #25
0
        public IActionResult UpdateBookForAnAuthor(Guid authorId, Guid id,
                                                   [FromBody] BookForUpdateDto book)
        {
            if (book == null)
            {
                return(BadRequest());
            }

            if (book.Description == book.Title)
            {
                ModelState.AddModelError(nameof(BookForUpdateDto),
                                         "Tytuł i opis są takie same");
            }

            if (!ModelState.IsValid)
            {
                // return 422
                return(new UnprocessableEntityObjectResult(ModelState));
            }

            if (!_libraryRepository.AuthorExists(authorId))
            {
                return(NotFound());
            }

            var bookForAuthorFromRepo = _libraryRepository.GetBookForAuthor(authorId, id);

            if (bookForAuthorFromRepo == null)
            {
                var bookToAdd = Mapper.Map <Book>(book);
                bookToAdd.Id = id;

                _libraryRepository.AddBookForAuthor(authorId, bookToAdd);

                if (!_libraryRepository.Save())
                {
                    throw new Exception($"Upserting book {id} for author {authorId} failed on save");
                }
                var bookToReturn = Mapper.Map <BookDto>(bookToAdd);

                return(CreatedAtRoute("GetBookForAuthor",
                                      new { authorId, id = bookToReturn.Id }
                                      , bookToReturn));
            }

            // map
            Mapper.Map(book, bookForAuthorFromRepo);
            // apply update
            _libraryRepository.UpdateBookForAuthor(bookForAuthorFromRepo);

            if (!_libraryRepository.Save())
            {
                throw new Exception($"Updating book {id} for {authorId} failed on save");
            }

            return(NoContent());
        }
コード例 #26
0
        public async Task <ActionResult <BookDto> > CreateBook(BookForUpdateDto bookForUpdateDto)
        {
            var book = _mapper.Map <Book>(bookForUpdateDto);
            await _repository.Add <Book>(book);

            var bookDto = _mapper.Map <BookDto>(book);

            return(CreatedAtAction(nameof(GetBook), new { id = bookDto.Id }, bookDto));
        }
コード例 #27
0
        public async Task <IActionResult> UpdateBook(int id, BookForUpdateDto bookDto)
        {
            var book = await _repository.GetById <Book>(id);

            _mapper.Map(bookDto, book);
            await _repository.SaveAll();

            return(NoContent());
        }
コード例 #28
0
        public async Task <ActionResult> PartiallyUpdateBookForAuthor(long authorId, long bookId,
                                                                      JsonPatchDocument <BookForUpdateDto> patchDocument)
        {
            var author = await _messages.Dispatch(new GetAuthorQuery(authorId));

            if (author is null)
            {
                return(NotFound($"No author with id {authorId} was found."));
            }

            var bookForAuthorFromRepo = await _messages.Dispatch(new GetBookQuery(authorId, bookId));

            if (bookForAuthorFromRepo == null)
            {
                var bookDto = new BookForUpdateDto();
                patchDocument.ApplyTo(bookDto, ModelState);

                if (!TryValidateModel(bookDto))
                {
                    return(ValidationProblem(ModelState));
                }

                var addCommand = new CreateBookCommand(bookDto.Title, bookDto.Description, authorId);

                Result <Book> addResult = await _messages.Dispatch(addCommand);

                if (addResult.IsFailure)
                {
                    return(BadRequest(addResult.Error));
                }

                var bookToReturn = _mapper.Map <BookDto>(addResult.Value);
                return(CreatedAtRoute(nameof(GetBookForAuthor),
                                      new { authorId, bookId = bookToReturn.Id }, bookToReturn));
            }

            var bookToPatch = _mapper.Map <BookForUpdateDto>(bookForAuthorFromRepo);

            // add validation
            patchDocument.ApplyTo(bookToPatch, ModelState);

            if (!TryValidateModel(bookToPatch))
            {
                return(ValidationProblem(ModelState));
            }

            var updateCommand = new UpdateBookCommand(bookId, bookToPatch.Title, bookToPatch.Description, authorId);

            Result <Book> updateResult = await _messages.Dispatch(updateCommand);

            if (updateResult.IsFailure)
            {
                return(BadRequest(updateResult.Error));
            }

            return(NoContent());
        }
        public IActionResult UpdateBookForAuthor(Guid authorId, Guid bookId,
                                                 [FromBody] BookForUpdateDto book)
        {
            if (book == null)
            {
                return(BadRequest());
            }

            if (book.Description == book.Title)
            {
                ModelState.AddModelError(nameof(BookForUpdateDto),
                                         "The provided description should be different from the title.");
            }

            //Model State is a dictionary contains both of the model and model binding validation,
            //it also contains a collection of error messages for each value submitted
            if (!ModelState.IsValid)
            {//Validation
                return(new UnprocessableEntityObjectResult(ModelState));
            }

            if (!_libraryRepository.AuthorExists(authorId))
            {
                return(NotFound());
            }

            var bookForAuthorFromRepo = _libraryRepository.GetBookForAuthor(authorId, bookId);

            if (bookForAuthorFromRepo == null) //upserting
            {                                  //Create a variable that is mapped from type Book and the variable used is book because we want the data that in the request body
                var bookToAdd = Mapper.Map <Book>(book);
                bookToAdd.Id = bookId;

                _libraryRepository.AddBookForAuthor(authorId, bookToAdd);
                if (!_libraryRepository.Save())
                {
                    throw new Exception($"Upserting book {bookId}, for author {authorId} failed on saving");
                }

                var bookToReturn = Mapper.Map <BookDto>(bookToAdd);

                return(CreatedAtRoute("GetBookForAuthor",
                                      new { authorId = authorId, bookId, bookToReturn.Id }
                                      , bookToReturn));
            }

            Mapper.Map(book, bookForAuthorFromRepo);

            _libraryRepository.UpdateBookForAuthor(bookForAuthorFromRepo);

            if (!_libraryRepository.Save())
            {
                throw new Exception($"Updating book {bookId} for author {authorId} failed on saving");
            }

            return(NoContent());
        }
コード例 #30
0
        public IActionResult PartiallyUpdateBookForAuthor(Guid authorId, Guid id, [FromBody] JsonPatchDocument <BookForUpdateDto> patchDoc)
        {
            if (patchDoc == null)
            {
                return(BadRequest());
            }

            if (!libraryRepository.AuthorExists(authorId))
            {
                return(NotFound());
            }

            var bookFromAuthor = libraryRepository.GetBookForAuthor(authorId, id);

            if (bookFromAuthor == null)
            {
                var book = new BookForUpdateDto();

                patchDoc.ApplyTo(book);

                var bookToAdd = Mapper.Map <Book>(book);
                bookToAdd.Id = id;

                libraryRepository.AddBookForAuthor(authorId, bookToAdd);

                if (!libraryRepository.Save())
                {
                    throw new Exception($"Upserting book {id} for author {authorId} failed on save");
                }

                var bookToReturn = Mapper.Map <BookDto>(bookToAdd);

                return(CreatedAtAction(
                           nameof(GetBookForAuthor),
                           new { authorId, id = bookToReturn.Id },
                           bookToReturn));
            }
            //return NotFound();

            var bookToPatch = Mapper.Map <BookForUpdateDto>(bookFromAuthor);

            patchDoc.ApplyTo(bookToPatch);

            //add validation

            Mapper.Map(bookToPatch, bookFromAuthor);

            libraryRepository.UpdateBookForAuthor(bookFromAuthor);

            if (!libraryRepository.Save())
            {
                throw new Exception($"Patching a book {id} for author {authorId} failed on save");
            }

            return(NoContent());
        }