コード例 #1
0
        public IHttpActionResult PostBook([FromBody] BookPostBindingModel bookPost)
        {
            if (!this.ModelState.IsValid)
            {
                return(this.BadRequest(this.ModelState));
            }

            var context      = new BookShopContext();
            var categories   = bookPost.Categories.Split(' ').Select(c => c.Trim()).ToList();
            var categoryList = new List <Category>();

            categories.ForEach(c =>
            {
                var categoryDb = context.Categories.FirstOrDefault(ca => ca.Name == c);
                if (categoryDb == null)
                {
                    categoryList.Add(new Category()
                    {
                        Name = c
                    });
                }
                else
                {
                    categoryList.Add(categoryDb);
                }
            });

            var newBook = new Book()
            {
                Title          = bookPost.Title,
                Decription     = bookPost.Decription,
                Price          = bookPost.Price,
                Copies         = bookPost.Copies,
                EditionType    = bookPost.EditionType,
                AgeRestriction = bookPost.AgeRestriction,
                ReleaseDate    = bookPost.ReleaseDate,
                Categories     = categoryList,
                AuthorId       = 1
            };

            context.Books.Add(newBook);
            context.SaveChanges();

            return(this.Ok(bookPost));
        }
コード例 #2
0
        public IHttpActionResult PostBook(BookPostBindingModel newBook)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }
            var book = new Book()
            {
                Title = newBook.Title,
                Description = newBook.Description,
                Price = newBook.Price,
                Copies = newBook.Copies,
                EditionType = newBook.EditionType,
                AgeRestriction = newBook.AgeRestriction,
                ReleaseDate = newBook.ReleaseDate,
                AuthorId = newBook.AuhtorId,
            };

            foreach (var category in newBook.Categories)
            {
                if (_db.Categories.Any(c => c.Name == category))
                {
                    book.Categories.Add(_db.Categories.FirstOrDefault(c => c.Name == category));
                }
                else
                {
                    var newCategory = new Category();
                    newCategory.Name = category;
                    book.Categories.Add(newCategory);
                }
            }

            _db.Books.Add(book);
            _db.SaveChanges();

            return this.Ok(new { id = book.Id, isCreated = true });
        }