【问题标题】:Why do these two queries return different results in Entity Framework?为什么这两个查询在 Entity Framework 中返回不同的结果?
【发布时间】:2012-03-16 16:57:09
【问题描述】:

我在Entity Framework中写了如下查询,值不一样。

var query = from p in db.Parents
            let children = p.Children
            let grandchildren = children.SelectMany(c => c.Grandchildren)
            select new 
            {
                Count1 = children.Count(c => !c.Grandchildren.Any()),
                Count2 = children.Count(c => !grandchildren.Any())
            };

Count1 属性返回我所期望的,而 Count2 没有。

我正在尝试返回没有任何 Grandchild 对象的 Children 的数量。在这种情况下,Count2 似乎返回 0,但 Count1 使用以下数据集返回 1:

父母

Id
------  
1

孩子

Id    ParentId
--------------
1     1
2     1

孙子

Id    ChildId
-------------
1     1

我有两个孩子,其中只有一个有孩子。为什么第二个查询似乎不像我认为的那样工作?

我的对象如下:

public class Parent {
    public int Id { get; set; }
    public virtual ICollection<Child> Children { get; set; }
}

public class Child { 
    public int Id { get; set; }
    public int ParentId { get; set; }
    public virtual ICollection<Grandchild> Grandchildren { get; set; }
}

public class Grandchild {
    public int Id { get; set; }
    public int ChildId { get; set; }
}

【问题讨论】:

    标签: c# linq entity-framework linq-to-entities


    【解决方案1】:
    grandchildren.Any()
    

    如果您的grandchildren 集合中有任何对象,则只是返回。因此,除非您的 SelectMany 返回零结果,否则它将始终返回 true。

    因此,除了Count2 = 0,您将永远不会得到任何结果,因为如果有任何结果,!grandChildren.Any() 将等于 0。

    【讨论】:

    • 所以,!grandChildren.Any() 将始终返回 0
    【解决方案2】:

    问题在于您的 grandchildren 范围变量。它包含所有个孙子(没有过滤到特定的子),所以 Count2 总是考虑整个树中是否有任何个孙子。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多