微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用EF Core 5.0加载自引用实体只需在其导航属性中获取父级及其子级

如何解决使用EF Core 5.0加载自引用实体只需在其导航属性中获取父级及其子级

我想实现一个评论系统,这是我的评论实体。

 public class Comment
    {
        public int CommentId { get; set; }
        public int? ParentId  { get; set; }
        public string Content { get; set; }
        public DateTimeOffset DateCreated { get; set; }
        public DateTimeOffset DateModified { get; set; }


        public Comment Parent { get; set; }
        public ICollection<Comment> Children { get; set; }


    }

这是我在Fluent API中的配置


        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            modelBuilder.Entity<Comment>(comment =>
            {
                comment.HasKey(c => c.CommentId);
                comment.HasIndex(c => c.ParentId);

                comment.HasOne(c => c.Parent)
                       .WithMany(c => c.Children)
                       .HasForeignKey(c => c.ParentId);
            });
        }

一切正常,我可以使用此代码加载具有层次结构的所有记录(包括父级和子级)

  List<Comment> comments = await _db.Comments.Include(c => c.Children)
                .ToListAsync();

但是此代码加载所有元素,例如子元素。但是我想让所有的父母,然后是他们的孩子,然后是大孩子,再到...。

在这种情况下,我使用此代码

List<Comment> comments = await _db.Comments.Include(c => c.Children)
                .Where(c => c.ParentId == null)
                .ToListAsync();

并且此代码仅将所有父母及其子女加载,而不是大孩子,并且在层次结构中加载更多内容

我应该如何编写此查询

解决方法

我找到了针对这种情况的解决方案。

  public async Task<IActionResult> Index()
        {

            List<Comment> comments = await _db.Comments.AsNoTrackingWithIdentityResolution()
                                                        .Include(c => c.Children)
                                                        .ToListAsync();

            // Structure Comments into a tree
            List<Comment> commentsTree = comments.Where(c => c.ParentId == null)
                                                 .AsParallel()
                                                 .ToList();

            return View(commentsTree);
        }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。