Armin Shoeibi
Armin Shoeibi

Reputation: 670

Load Self Referencing Entity With EF Core 5.0 ( Just get Parents and their children in their navigation property )

I want to implement a Commenting System this is my Comment Entity.

 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; }


    }

and this is my configs in 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);
            });
        }

everything is ok and I can load all records with hierarchy ( include parent and children ) with this code

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

but this code load all elements such as children. But I want to load all Parents and then their childs and then grand childs and ....

I use this code for this scenario

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

and this code just load all parents with their children and not grand chilren and more in hierarchy.

How should I write this query ?

Upvotes: 2

Views: 2674

Answers (1)

Armin Shoeibi
Armin Shoeibi

Reputation: 670

I found solution for this scenario.

  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);
        }

Upvotes: 2

Related Questions