Very similar to the following question but I want to filter on a grandchild of the parent object i.e. do something similar to
db.Parents
.Where(p => p.Age > 70)
.Include(p => p.Children.GrandChildren)
.Where(p => p.GrandChildren.Any(gc => gc.Age >= 5))
The marked answer works correctly but how to extend it for my scenario? Also I would like to make just one database call, is this possible with EF?
I don't know if it makes a difference but my children and grandchildren properties are collections.
I currently have code similar to what's below, which does not work!
var query = this.dbContext.Parent.AsNoTracking()
.Where(p => p.Age > 70)
.Select(p=> new
{
Parent = p,
FirstChild = p.FirstChild,
ChildrenCollection = p.ChildrenCollection
GrandChildrenCollection = p.ChildrenCollection.SelectMany(cc => cc.GrandChildren)
}).FirstOrDefault();
It fails with an InvalidOperationException, message "Additional information: Member 'CurrentValues' cannot be called for the entity of type 'GrandChildren' because the entity does not exist in the context. To add an entity to the context call the Add or Attach method of DbSet."