0

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."

Community
  • 1
  • 1
Mayoweezy
  • 537
  • 1
  • 8
  • 21
  • Is GrandChildren entity mapped correctly to table name? Have you linked Parent-Children-GrandChildren tables correctly? – Logar314159 Jan 15 '16 at 18:59
  • @Logar314159 Yes, the GrandChildren entity is mapped correctly to the tablename. – Mayoweezy Jan 15 '16 at 19:00
  • @Logar314159 In calls where I don't need to filter on the grandchildren, the works correctly, so I am pretty certain the tables are linked correctly via primary keys `var query = this.dbContext.Parent.Where(p => p.Age > 70) .Include(bd => bd.ChildrenCollection.Select(og => og.ChildrenCollection.Select(bo => bo.OrderBroker))) .Include(bd => bd.FirstChild); var parentFound = query.FirstOrDefault(); return parentFound;` – Mayoweezy Jan 15 '16 at 19:20

0 Answers0