首页 .Net 九、Abp vNext 基础篇丨评论聚合功能

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

系列文章列表,点击展示/隐藏

系列教程一目录:知识点源码解析

系列教程二目录:Bcvp AbpVnext讲解

系列教程三目录:单个知识点讲解

系列教程四目录:分库分表(日志系统案例讲解)

本文梯子

    正文

    介绍

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

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

    评论仓储接口和实现

       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 >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 >CommentWithRepliesDto
        {
            public CommentWithDetailsDto Comment { get; set; }
    
            public List<CommentWithDetailsDto> Replies { get; set; } = new List<CommentWithDetailsDto>();
        }
    
        public >CommentWithDetailsDto : FullAuditedEntityDto<Guid>
        {
            public Guid? RepliedCommentId { get; set; }
    
            public string Text { get; set; }
    
            public BlogUserDto Writer { get; set; }
        }
    
        public >CreateCommentDto
        {
            public Guid? RepliedCommentId { get; set; }
    
            public Guid PostId { get; set; }
    
            [Required]
            public string Text { get; set; }
        }
    
        public >UpdateCommentDto
        {
            [Required]
            public string Text { get; set; }
        }
    
    

    接口实现

    
       public >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

    公众号

    特别声明:本站部分内容收集于互联网是出于更直观传递信息的目的。该内容版权归原作者所有,并不代表本站赞同其观点和对其真实性负责。如该内容涉及任何第三方合法权利,请及时与824310991@qq.com联系,我们会及时反馈并处理完毕。