简体   繁体   中英

EF Core included nested self-referencing list

I have an entity looking like this:

public class Comment
{
    public Guid Id { get; set; }
    public DateTime PublishedDate { get; set; }
    public string CommentText { get; set; }
    public bool IsEdited { get; set; }
    public bool IsDeleted { get; set; }
    public ICollection<Comment> Replies { get; set; }



    public int? ParentBlogId { get; set; }
    [ForeignKey("ParentBlogId")]
    public BlogPost ParentBlog { get; set; }

    public Guid? ParentCommentId { get; set; }
    [ForeignKey("ParentCommentId")]
    public Comment ParentComment { get; set; }

    public string UserId { get; set; }
    [ForeignKey("UserId")]
    public User User { get; set; }
}

Now as you see this contains an ICollection of the same type. So a comment can have multiple comments under it. When I want to load all these in a nice nested list I tried using this:

var comments = await _context.Comments
                .Include(x => x.User)
                .Include(x => x.Replies)
                 .ThenInclude(x => x.User).ToListAsync();

The problem is that this only loads 2 levels deep. So if I have a structure like this:

Comment
Comment
    Comment
        Comment
        Comment
    Comment
Comment

It will only load the first 2 levels:

Comment
Comment
    Comment
    Comment
Comment

How can I make it include all the replies of subreplies?

I did it by calling a recursive method:

    public async Task<List<Comment>> GetAsync(int blogId)
    {
        var comments = await _context.Comments
            .Include(x => x.User)
            .OrderByDescending(x => x.PublishedDate)
            .Where(x => x.ParentBlog.Id == blogId && !x.IsDeleted).ToListAsync();

        comments = await GetRepliesAsync(comments);


        return comments;
    }


    private async Task<List<Comment>> GetRepliesAsync(List<Comment> comments)
    {
        foreach (var comment in comments)
        {
            var replies = await GetFromParentIdAsync(comment.Id);
            if (replies != null)
            {
                comment.Replies = await GetRepliesAsync(replies.ToList());
            }
        }

        return comments;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM