EF Core 包含嵌套的自引用列表

EF Core included nested self-referencing list

我有一个看起来像这样的实体:

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

现在如您所见,它包含一个相同类型的 ICollection。所以一个评论下可以有多个评论。当我想将所有这些加载到一个漂亮的嵌套列表中时,我尝试使用这个:

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

问题是这只会加载 2 层深。所以如果我有这样的结构:

Comment
Comment
    Comment
        Comment
        Comment
    Comment
Comment

它只会加载前 2 个级别:

Comment
Comment
    Comment
    Comment
Comment

如何让它包含子回复的所有回复?

我是通过调用递归方法做到的:

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