public IHttpActionResult PutBook(int id, [FromUri] PutBookBindingModel bookModel) { var book = context.Books.Find(id); if (book == null) { return(this.BadRequest("Book doesn't exist")); } if (!this.ModelState.IsValid) { return(this.BadRequest(this.ModelState)); } var author = context.Authors.FirstOrDefault(a => a.Id == bookModel.AuthorId); if (author == null) { return(this.BadRequest("Author doesn't exist in the provided book.")); } book.Title = bookModel.Title; book.Description = bookModel.Description; book.Price = bookModel.Price; book.Copies = bookModel.Copies; book.Edition = bookModel.Edition; book.AuthorId = bookModel.AuthorId; context.Books.AddOrUpdate(book); context.SaveChanges(); var viewBook = new GetBookViewModel() { Title = book.Title, Description = book.Description, Price = book.Price, Copies = book.Copies, AuthorId = book.AuthorId, AuthorName = book.Author.FirstName, Edition = book.Edition, Categories = book.Categories.Select(c => c.Name) }; return(this.Ok(viewBook)); }
public IHttpActionResult PutBook(int id, [FromBody] PutBookBindingModel bookBindingModel) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } Author author = context.Authors.Find(bookBindingModel.AuthorId); if (author == null) { return(BadRequest("No author with specified AuthorId.")); } var book = new Book(id, bookBindingModel.Title, bookBindingModel.Description, bookBindingModel.EditionType, bookBindingModel.Price, bookBindingModel.Copies, bookBindingModel.ReleaseDate, author.Id); context.Entry(book).State = EntityState.Modified; try { context.SaveChanges(); } catch (DbUpdateConcurrencyException) { if (!BookExists(id)) { return(NotFound()); } else { throw; } } return(StatusCode(HttpStatusCode.NoContent)); }