简体   繁体   English

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

[英]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. 现在,您看到它包含相同类型的ICollection。 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. 问题在于,这只会加载2个级别的深度。 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;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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