public async Task <IActionResult> Put(string slug, [FromBody] BlogPostUpdateItem post) { if (slug == null || !(await postRepository.PostExistsAsync(slug))) { return(NotFound()); } await postRepository.UpdatePostAsync(slug, post); return(Ok()); }
public Task UpdatePostAsync(string slug, BlogPostUpdateItem post) { return(Task.Run(() => { var oldPost = dbContext.Posts .Include(x => x.PostTags) .FirstOrDefault(x => x.Slug == slug); if (oldPost == null) { return; } if (string.IsNullOrEmpty(post.BlogPost.Title) || post.BlogPost.Title.Equals(oldPost.Title)) { oldPost.Description = post.BlogPost.Description ?? oldPost.Description; oldPost.Body = post.BlogPost.Body ?? oldPost.Body; oldPost.UpdatedAt = DateTime.Now; dbContext.Update(oldPost); } else { List <Entities.PostTag> updatedPostTags = new(); var newSlug = UtilityService.GenerateSlug(post.BlogPost.Title); foreach (var postTag in oldPost.PostTags) { updatedPostTags.Add(new Entities.PostTag { PostSlug = newSlug, TagSlug = postTag.TagSlug }); } var newPost = new Entities.Post { Slug = newSlug, Title = post.BlogPost.Title ?? oldPost.Title, Description = post.BlogPost.Description ?? oldPost.Description, Body = post.BlogPost.Body ?? oldPost.Body, CreatedAt = oldPost.CreatedAt, //UpdatedAt = DateTime.Now, PostTags = updatedPostTags }; dbContext.Remove(oldPost); dbContext.Posts.Add(newPost); } dbContext.SaveChanges(); })); }