예제 #1
0
        public IHttpActionResult PostPost(PostModel post)
        {
            // Validate request
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            // Check that the corresponding blog exists
            if (!_blogRepository.Any(b => b.BlogID == post.BlogID))
            {
                throw new Exception("Unable to add the post to the database, as it does not correspond to a blog");
            }

            //Set up new Post object, populated from input post
            Post dbPost = new Post();

            dbPost.Update(post);

            // Add the new Post object to the DB
            _postRepository.Add(dbPost);

            // Save the changes in the database
            try
            {
                _unitOfWork.Commit();
            }
            catch (Exception e)
            {
                throw new Exception("Unable to add the post to the database", e);
            }

            // Set post ID in PostModel object with the ID
            //  that was set in the DB post after db.SaveChanges
            post.PostID = dbPost.PostID;
            return(CreatedAtRoute("DefaultApi", new { id = post.PostID }, post));
        }