【发布时间】:2018-04-03 01:53:18
【问题描述】:
我有一个看起来像这样的实体:
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。所以一个评论下可以有多个 cmets。当我想将所有这些加载到一个漂亮的嵌套列表中时,我尝试使用它:
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
如何让它包含子回复的所有回复?
【问题讨论】:
-
这些都不行。如我的示例所示,急切加载不起作用。由于 Select 语句,投影也不能。显式加载不起作用,因为我想要一个列表,而不是单个对象。并且 EF Core 中不存在延迟加载
-
我很确定
_context.Comments.ToList()将加载所有级别。你确定你没有应用一些过滤器吗? -
或者加载单个评论的所有孙子,例如
_context.Comments.Where( r => loadedComment.Replies.Select(c => c.Id).ToList().Contains(r.ParentCommentId).AsEnumerable().Last();
标签: c# entity-framework ef-core-2.0