I have written the following query in Entity Framework and the values are different.
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())
};
The Count1 property returns what I expect, Count2 does not.
I am trying to return the number of Children that do not have any Grandchild objects. Count2 seems to return 0 in this case, but Count1 returns 1 with the following data set:
Parents
Id
------
1
Child
Id ParentId
--------------
1 1
2 1
Grandchild
Id ChildId
-------------
1 1
I have two children, only one of them has any children. Why does the second query not seem to work the way I think it should?
My objects are as follows:
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; }
}
is simply returning if there are any objects in your
grandchildrencollection. So it will always return true unless yourSelectManyreturns zero results.So, you will never get anything but
Count2 = 0because if there are any results!grandChildren.Any()will equal 0.