Dismissile
Dismissile

Reputation: 33071

Why do these two queries return different results in Entity Framework?

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; }
}

Upvotes: 0

Views: 281

Answers (2)

Keith
Keith

Reputation: 21224

The problem is with your grandchildren range variable. It contains all grandchildren (not filtered to a specific child), so Count2 is always considering if there are any grandchildren in the entire tree.

Upvotes: 0

naspinski
naspinski

Reputation: 34687

grandchildren.Any()

is simply returning if there are any objects in your grandchildren collection. So it will always return true unless your SelectMany returns zero results.

So, you will never get anything but Count2 = 0 because if there are any results !grandChildren.Any() will equal 0.

Upvotes: 1

Related Questions