public IHttpActionResult AddBook(BookAddBindingModel bookAddBindingModel) { if (!this.ModelState.IsValid) { return this.BadRequest(this.ModelState); } var categoryNames = bookAddBindingModel.Categories.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries); var categories = this.context.Categories.Where(c => categoryNames.Contains(c.Name)).ToList(); this.context.Books.Add(new Book() { Title = bookAddBindingModel.Title, AuthorId = bookAddBindingModel.AuthorId, Categories = categories, Copies = bookAddBindingModel.Copies, Description = bookAddBindingModel.Description, AgeRestriction = bookAddBindingModel.AgeRestriction, Edition = bookAddBindingModel.Edition, Price = bookAddBindingModel.Price, ReleaseDate = bookAddBindingModel.ReleaseDate }); try { this.context.SaveChanges(); return this.Ok("Book added successfully"); } catch (Exception) { return this.BadRequest(); } }
public IHttpActionResult AddBook(BookAddBindingModel bookAddBindingModel) { if (!this.ModelState.IsValid) { return(this.BadRequest(this.ModelState)); } var categoryNames = bookAddBindingModel.Categories.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries); var categories = this.context.Categories.Where(c => categoryNames.Contains(c.Name)).ToList(); this.context.Books.Add(new Book() { Title = bookAddBindingModel.Title, AuthorId = bookAddBindingModel.AuthorId, Categories = categories, Copies = bookAddBindingModel.Copies, Description = bookAddBindingModel.Description, AgeRestriction = bookAddBindingModel.AgeRestriction, Edition = bookAddBindingModel.Edition, Price = bookAddBindingModel.Price, ReleaseDate = bookAddBindingModel.ReleaseDate }); try { this.context.SaveChanges(); return(this.Ok("Book added successfully")); } catch (Exception) { return(this.BadRequest()); } }
public IHttpActionResult AddBook([FromBody] BookAddBindingModel book) { var author = context.Authors.Find(book.AuthorId); if (author == null) { return(this.BadRequest("Invalid author Id")); } var newBook = new Book() { Title = book.Title, Description = book.Description, Price = book.Price, Copies = book.Copies, Edition = book.Edition, ReleaseDate = book.ReleaseDate, AuthorId = book.AuthorId, Author = author }; string[] categories = book.Categories.Split(' '); foreach (string category in categories) { if (!context.Categories.Any(c => c.Name == category)) { return(this.BadRequest("Invalid category name " + category)); } newBook.Categories.Add(context.Categories.Where(c => c.Name == category).First()); } context.Books.Add(newBook); context.SaveChanges(); return(this.Ok(new BookViewModel(newBook))); }