过滤自引用实体中的子项

时间:2013-02-22 14:16:11

标签: entity-framework

我有这个评论模型,每个评论都可以作为另一条评论的答案。

 public class Comment
 {
    public virtual int Id { get; set; }
    public virtual string Body { get; set; }
    public virtual DateTime? AddedDate { get; set; }
    public virtual bool IsApproved { get; set; }
    public virtual int LikeCount { get; set; }
    public virtual User User { get; set; }
    public virtual AnonymousUser AnonymousUser { get; set; }
    public virtual Post Post { get; set; }
    public virtual Page Page { get; set; }
    public virtual int? ParentId { get; set; }
    public virtual Comment Parent { get; set; }
    public ICollection<Comment> Children { get; set; }
    public virtual byte[] RowVersion { get; set; }
 }

我尝试使用此代码来获取“IsApproved == true”

的注释
this._comments
            .Where(comment => comment.Post.Id == postId).Include(comment => comment.User)
            .Include(comment => comment.AnonymousUser)
            .Include(comment => comment.Children).Where(comment => comment.IsApproved == true)
            .OrderBy(comment => comment.AddedDate)
            .Skip(page * count)
            .Take(count).ToList()
            .Where(comment => comment.Parent == null).ToList();

但是此查询只返回“IsApproved == true”的 root 注释。

即使是孩子,我也会采取什么措施来过滤所有评论。

由于

2 个答案:

答案 0 :(得分:0)

在过滤孩子时尝试任意。

this._comments
            .Where(comment => comment.Post.Id == postId).Include(comment => comment.User)
            .Include(comment => comment.AnnonymousUser)
            .Where(comment => comment.Children.Any(child=>child.IsApproved == true))
            .OrderBy(comment => comment.AddedDate)
            .Skip(page * count)
            .Take(count).ToList()
            .Where(comment => comment.Parent == null).ToList();

答案 1 :(得分:0)

由于.Where(comment => comment.Parent == null),它只返回根评论。

但总的来说......

如果我理解正确你想要获得批准并在特定职位上的所有评论(包括儿童评论),我是对的吗?

假设: 每个评论都有人口填充 - 甚至是孩子。

this._comments
        .Include(comment => comment.User)
        .Include(comment => comment.AnnonymousUser)
        .Include(comment => comment.Children)
        .Where(comment => comment.IsApproved && comment.Post.Id == postId)
        .OrderBy(comment => comment.AddedDate)
        .Skip(page * count)
        .Take(count)
        .ToList();

编辑:

或者,如果您只想过滤那些已获批准的子项,请查看本文http://msdn.microsoft.com/en-us/data/jj574232.aspx在明确加载相关实体时应用过滤器