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

时间:2018-02-08 13:08:47

标签: c# entity-framework ef-core-2.0

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

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

如何使其包含子目录的所有回复?

1 个答案:

答案 0 :(得分:0)

我是通过调用递归方法完成的:

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