entity-framework-coreef-core-2.2entity-framework-plus

How to filter grand children using EF PLUS


I want get to Parent and its only active Children and active Grand Children using Entityframework Plus

Relationship
Parent -> Children -> GrandChildren

var parent = await _dbContext.Parent
             .IncludeFilter(p=>p.Children.Where(c=>c.IsActive == true))
             .IncludeFilter(p=>p.Children.Select(c=>c.GrandChildren.Where(gc=>gc.IsActive ==true)))
             .Where(p=>p.ParnetID == 1234)
             .SingleOrDefaultAsync()

The above query does not work. The children does not get filtered. It returns all Children including inactive children. However GrandChildren gets filtered( however i am guessing grand childeren are getting filtered in memory not in sql)


Solution

  • You must include the filter as well on the Children the second time you use IncludeFilter, otherwise, you will include the Children unfiltered.

    var parent = await _dbContext.Parent
                 .IncludeFilter(p=>p.Children.Where(c=>c.IsActive == true))
                 .IncludeFilter(p=>p.Children.Where(c=>c.IsActive == true).Select(c=>c.GrandChildren.Where(gc=>gc.IsActive ==true)))
                 .Where(p=>p.ParnetID == 1234)
                 .SingleOrDefaultAsync()