public async Task <BlogPostVM> Update(BlogPostUpdateVM request, string slug)
        {
            using var db = new SQLiteDBContext();

            var blogPost = await db.BlogPosts.Include(x => x.Tags).FirstOrDefaultAsync(bp => bp.Slug == slug) ?? throw new NotFoundException(slug);

            #region IfTitleHasChanged

            if (request.Title != blogPost.Title && !string.IsNullOrEmpty(request.Title))
            {
                var tags = new List <BlogPostTag>(blogPost.Tags);
                //Delete all referenced entities
                foreach (var item in blogPost.Tags)
                {
                    db.BlogPostTags.Remove(item);
                }
                await db.SaveChangesAsync();

                blogPost.Tags = null;
                db.BlogPosts.Remove(blogPost);
                await db.SaveChangesAsync();

                //Add the post again with all the tags
                SlugHelper helper = new SlugHelper();
                blogPost.Slug = helper.GenerateSlug(request.Title);

                await db.BlogPosts.AddAsync(blogPost);

                await db.SaveChangesAsync();

                foreach (var tag in tags)
                {
                    var postTag = new BlogPostTag()
                    {
                        TagId = tag.TagId, BlogPostId = blogPost.Slug
                    };
                    await db.BlogPostTags.AddAsync(postTag);
                }
                await db.SaveChangesAsync();

                blogPost.Tags = tags;
            }
            #endregion

            blogPost.UpdatedAt = DateTime.UtcNow;
            mapper.Map(request, blogPost);

            db.BlogPosts.Update(blogPost);
            await db.SaveChangesAsync();

            var response = mapper.Map <BlogPostVM>(blogPost);

            return(response);
        }
Exemple #2
0
        public async Task <ActionResult <BlogPostVM> > Update(BlogPostUpdateVM request, string slug)
        {
            var result = await _blogPostService.Update(request, slug);

            if (result == null)
            {
                return(BadRequest());
            }

            return(Ok(result));
        }