九、Abp vNext 基础篇丨评论聚合功能

介绍

评论本来是要放到标签里面去讲的,但是因为上一章东西有点多了,我就没放进去,这一章单独拿出来,内容不多大家自己写写就可以,也算是对前面讲解的一个小练习吧。

相关注释我也加在代码上面了,大家看看代码都可以理解。

评论仓储接口和实现

   public interface ICommentRepository : IBasicRepository<Comment, Guid>
    {
        /// <summary>
        /// 根据文章Id 获取评论
        /// </summary>
        /// <param name="postId"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        Task<List<Comment>> GetListOfPostAsync(Guid postId, CancellationToken cancellationToken = default);
        /// <summary>
        /// 根据文章Id 获取评论数量
        /// </summary>
        /// <param name="postId"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        Task<int> GetCommentCountOfPostAsync(Guid postId, CancellationToken cancellationToken = default);
        /// <summary>
        /// 根据评论Id 下面的子获取评论
        /// </summary>
        /// <param name="id"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        Task<List<Comment>> GetRepliesOfComment(Guid id, CancellationToken cancellationToken = default);

        Task DeleteOfPost(Guid id, CancellationToken cancellationToken = default);
    }



    public class EfCoreCommentRepository:EfCoreRepository<CoreDbContext, Comment, Guid>,ICommentRepository
    {
        public EfCoreCommentRepository(IDbContextProvider<CoreDbContext> dbContextProvider) : base(dbContextProvider)
        {
        }

        public async Task<List<Comment>> GetListOfPostAsync(Guid postId, CancellationToken cancellationToken = default)
        {
            return await (await GetDbSetAsync())
                .Where(a => a.PostId == postId)
                .OrderBy(a => a.CreationTime)
                .ToListAsync(GetCancellationToken(cancellationToken));
        }

        public async Task<int> GetCommentCountOfPostAsync(Guid postId, CancellationToken cancellationToken = default)
        {
            return await (await GetDbSetAsync())
                .CountAsync(a => a.PostId == postId, GetCancellationToken(cancellationToken));
        }

        public async Task<List<Comment>> GetRepliesOfComment(Guid id, CancellationToken cancellationToken = default)
        {
            return await (await GetDbSetAsync())
                .Where(a => a.RepliedCommentId == id).ToListAsync(GetCancellationToken(cancellationToken));
        }

        public async Task DeleteOfPost(Guid id, CancellationToken cancellationToken = default)
        {
            var recordsToDelete = await (await GetDbSetAsync()).Where(pt => pt.PostId == id).ToListAsync(GetCancellationToken(cancellationToken));
            (await GetDbSetAsync()).RemoveRange(recordsToDelete);
        }
    }


评论接口和Dto

    public interface ICommentAppService : IApplicationService
    {
        Task<List<CommentWithRepliesDto>> GetHierarchicalListOfPostAsync(Guid postId);

        Task<CommentWithDetailsDto> CreateAsync(CreateCommentDto input);

        Task<CommentWithDetailsDto> UpdateAsync(Guid id, UpdateCommentDto input);

        Task DeleteAsync(Guid id);
    }

    public class CommentWithRepliesDto
    {
        public CommentWithDetailsDto Comment { get; set; }

        public List<CommentWithDetailsDto> Replies { get; set; } = new List<CommentWithDetailsDto>();
    }

    public class CommentWithDetailsDto : FullAuditedEntityDto<Guid>
    {
        public Guid? RepliedCommentId { get; set; }

        public string Text { get; set; }

        public BlogUserDto Writer { get; set; }
    }

    public class CreateCommentDto
    {
        public Guid? RepliedCommentId { get; set; }

        public Guid PostId { get; set; }

        [Required]
        public string Text { get; set; }
    }

    public class UpdateCommentDto
    {
        [Required]
        public string Text { get; set; }
    }

接口实现


   public class CommentAppService : CoreAppService, ICommentAppService
    {
        private IUserLookupService<IdentityUser> UserLookupService { get; }

        private readonly ICommentRepository _commentRepository;
        private readonly IGuidGenerator _guidGenerator;

        public CommentAppService(ICommentRepository commentRepository, IGuidGenerator guidGenerator, IUserLookupService<IdentityUser> userLookupService)
        {
            _commentRepository = commentRepository;
            _guidGenerator = guidGenerator;
            UserLookupService = userLookupService;
        }

        public async Task<List<CommentWithRepliesDto>> GetHierarchicalListOfPostAsync(Guid postId)
        {
            // 获取评论数据
            var comments = await GetListOfPostAsync(postId);

            #region 对评论的作者进行赋值

            var userDictionary = new Dictionary<Guid, BlogUserDto>();

            foreach (var commentDto in comments)
            {
                if (commentDto.CreatorId.HasValue)
                {
                    var creatorUser = await UserLookupService.FindByIdAsync(commentDto.CreatorId.Value);

                    if (creatorUser != null && !userDictionary.ContainsKey(creatorUser.Id))
                    {
                        userDictionary.Add(creatorUser.Id, ObjectMapper.Map<IdentityUser, BlogUserDto>(creatorUser));
                    }
                }
            }

            foreach (var commentDto in comments)
            {
                if (commentDto.CreatorId.HasValue && userDictionary.ContainsKey((Guid)commentDto.CreatorId))
                {
                    commentDto.Writer = userDictionary[(Guid)commentDto.CreatorId];
                }
            }

            #endregion

            var hierarchicalComments = new List<CommentWithRepliesDto>();

            #region 包装评论数据格式

            // 评论包装成2级(ps:前面的查询根据时间排序,这里不要担心子集在父级前面)

            foreach (var commentDto in comments)
            {
                var parent = hierarchicalComments.Find(c => c.Comment.Id == commentDto.RepliedCommentId);

                if (parent != null)
                {
                    parent.Replies.Add(commentDto);
                }
                else
                {
                    hierarchicalComments.Add(new CommentWithRepliesDto() { Comment = commentDto });
                }
            }

            hierarchicalComments = hierarchicalComments.OrderByDescending(c => c.Comment.CreationTime).ToList();


            #endregion
          

            return hierarchicalComments;

        }

        public async Task<CommentWithDetailsDto> CreateAsync(CreateCommentDto input)
        {
            // 也可以使用这种方式(这里只是介绍用法) GuidGenerator.Create()
            var comment = new Comment(_guidGenerator.Create(), input.PostId, input.RepliedCommentId, input.Text);

            comment = await _commentRepository.InsertAsync(comment);

            await CurrentUnitOfWork.SaveChangesAsync();

            return ObjectMapper.Map<Comment, CommentWithDetailsDto>(comment);
        }

        public async Task<CommentWithDetailsDto> UpdateAsync(Guid id, UpdateCommentDto input)
        {
            var comment = await _commentRepository.GetAsync(id);

            comment.SetText(input.Text);

            comment = await _commentRepository.UpdateAsync(comment);

            return ObjectMapper.Map<Comment, CommentWithDetailsDto>(comment);
        }

        public async Task DeleteAsync(Guid id)
        {
            await _commentRepository.DeleteAsync(id);

            var replies = await _commentRepository.GetRepliesOfComment(id);

            foreach (var reply in replies)
            {
                await _commentRepository.DeleteAsync(reply.Id);
            }
        }


        private async Task<List<CommentWithDetailsDto>> GetListOfPostAsync(Guid postId)
        {
            var comments = await _commentRepository.GetListOfPostAsync(postId);

            return new List<CommentWithDetailsDto>(
                ObjectMapper.Map<List<Comment>, List<CommentWithDetailsDto>>(comments));
        }

    }


 CreateMap<Comment, CommentWithDetailsDto>().Ignore(x => x.Writer);

结语

说明:

  • 1.整个评论的实现非常简单,我们只是实现了一个2层的嵌套。
  • 2.下一章我们讲授权和策略大家应该会比较喜欢,加油

联系作者:加群:867095512 @MrChuJiu

九、Abp vNext 基础篇丨评论聚合功能

上一篇:xaf--导航菜单显示图标


下一篇:dos基础命令学习