[英]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
它只会加载前两个级别:
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.