我在弄清楚如何包含子属性列表时遇到了麻烦,该列表可以有自己的子属性列表。
我的实体设置如下:
public class Comment
{
[Key]
public Guid Id { get; set; }
//other properties
public Guid? ParentCommentId { get; set; }
public Comment ParentComment { get; set; }
public ICollection<Comment> ChildComments { get; set; }
[Required]
public Guid PostId { get; set; }
[Required]
public Post CommentForPost { get; set; }
[Required]
public Guid UserId { get; set; }
[Required]
public User CreatedBy { get; set; }
}
我有以下关系:
Post
-> Comment
之间的一对多关系User
-> Comment
之间的一对多关系Comment
-> Comment
之间的一对多关系我想做的是查询帖子的评论,包括父级评论以及所有父级的子级评论(即ICollection of ChildComments
属性)。
当前,我具有以下LINQ语句设置:
return _context.Comments.Include(comment => comment.CreatedBy)
.Include(comment => comment.ChildComments)
.ThenInclude(x => x.CreatedBy)
.Where(comment => comment.PostId == postId)
.OrderBy(comment => comment.Created)
.AsNoTracking();
问题是我也得到了重复。例如,如果我使用以下数据进行以上测试:
Comment1 {
Id = 1
ChildComments = Comment2
}
Comment2 {
Id = 2
ParentCommentId = 1
ChildComments = Comment3
}
Comment3 {
Id = 3
ParentCommentId = 2
ChildComments = null
}
Comment4 {
Id = 4
ChildComments = null
}
如果我使用上面的查询,最终我会跌倒。我想得到的只是父级注释的列表,以及他们所有的子注释(如果子注释有自己的子注释,也要包括它们)。
错误:
[
{
"id": "1",
"parentCommentId": null,
"childComments": [
{
"id": "2",
"parentCommentId": "1",
"childComments": [
{
"id": "3",
"parentCommentId": "2",
"childComments": []
}
]
}
]
},
{
"id": "2",
"parentCommentId": "1",
"childComments": [
{
"id": "3",
"parentCommentId": "2",
"childComments": []
}
]
},
{
"id": "3",
"parentCommentId": "2",
"childComments": []
},
{
"id": "4",
"parentCommentId": null,
"childComments": []
}
]
[
{
"id": "1",
"parentCommentId": null,
"childComments": [
{
"id": "2",
"parentCommentId": "1",
"childComments": [
{
"id": "3",
"parentCommentId": "2",
"childComments": []
}
]
}
]
},
{
"id": "4",
"parentCommentId": null,
"childComments": []
}
]
更新:我尝试为ParentCommentId == null
添加where子句,因此修改后的查询为:
return _context.Comments.Include(comment => comment.CreatedBy)
.Include(comment => comment.ChildComments)
.ThenInclude(x => x.CreatedBy)
.Where(comment => comment.PostId == postId)
.Where(comment => comment.ParentCommentId == null)
.OrderBy(comment => comment.Created)
.AsNoTracking();
但是问题是上面的linq语句使我没有孩子。即在上面的示例中,我无法获得正确的答案。
[
{
"id": "1",
"parentCommentId": null,
"childComments": [
{
"id": "2",
"parentCommentId": "1",
"childComments": []
}
]
},
{
"id": "4",
"parentCommentId": null,
"childComments": []
}
]