Ejemplo n.º 1
0
        public PostFullModel GetPost(int id)
        {
            Post post = db.Posts.Find(id);

            if (post == null)
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
            }

            var model = new PostFullModel()
            {
                Id          = post.Id,
                Title       = post.Title,
                PostContent = post.PostContent,
                PostDate    = post.PostDate,
                Categories  =
                    from cat in post.Categories
                    select new CategoryModel()
                {
                    Id   = cat.Id,
                    Name = cat.Name
                }
            };

            return(model);
        }
Ejemplo n.º 2
0
        public HttpResponseMessage CreatePost([FromBody] CreatePostModel item)
        {
            BlogContext context = new BlogContext();

            Post entity = new Post()
            {
                Content = item.Content,
                Title   = item.Title,
            };

            var categories = new HashSet <Category>();

            if (item.Categories != null)
            {
                foreach (string catName in item.Categories)
                {
                    Category cat = context.Categories.FirstOrDefault(c => c.Name == catName);

                    if (cat == null)
                    {
                        cat = new Category()
                        {
                            Name = catName,
                        };
                    }

                    categories.Add(cat);
                }
            }
            else
            {
                Category cat = context.Categories.FirstOrDefault(c => c.Name == "Default");
                if (cat == null)
                {
                    cat = new Category()
                    {
                        Name = "Default"
                    };
                }
                categories.Add(cat);
            }

            entity.Categories = categories;

            context.Posts.Add(entity);
            context.SaveChanges();

            PostFullModel model = new PostFullModel()
            {
                PostId     = entity.PostId,
                Title      = entity.Title,
                Content    = entity.Content,
                Categories = entity.Categories.Select(c => new CategoryModel()
                {
                    CategoryId = c.CategoryId,
                    Name       = c.Name,
                }),
            };

            HttpResponseMessage response = this.Request.CreateResponse(HttpStatusCode.Created, model);

            response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = model.PostId }));

            return(response);
        }