Пример #1
0
        public async Task <Post> CreatePostAsync(Post post, bool isPost)
        {
            var newSlug   = Utilities.Slugify(post.Title);
            var createdAt = Utilities.GetZuluOfNow();
            var newPost   = new Post
            {
                Slug        = newSlug,
                Title       = post.Title,
                Body        = post.Body,
                Description = post.Description,
                CreatedAt   = createdAt
            };

            if (!isPost)
            {
                newPost = post;
            }
            if (post.TagList != null)
            {
                if (isPost)
                {
                    newPost.Tags    = new List <Tag>();
                    newPost.TagList = new List <string>();
                }
                context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
                foreach (string tagName in post.TagList.ToArray())
                {
                    var tag = tagService.FindByName(tagName); //find tag by name
                    //context.Entry(tag).State = EntityState.Detached;
                    if (tag != null)                          //check is that tag already in db, if yes-then only create connection between tag and post
                    {
                        if (isPost)
                        {
                            postTagService.CreatePostTag(ref newPost, tag, tagName);
                        }
                    }
                    else     //if tag does not exist in db, create tag and create connection between post and tag
                    {
                        var id         = tagService.CreateTagAsync(tagName);
                        var createdTag = tagService.FindByName(tagName);
                        if (isPost)
                        {
                            postTagService.CreatePostTag(ref newPost, tag, tagName);
                        }
                        context.Entry(tag).State = EntityState.Detached;
                    }
                }
            }
            context.AttachRange(newPost.Tags);
            context.Posts.Add(newPost);
            await context.SaveChangesAsync();

            return(newPost);
        }