How to filter grand children using EF PLUS

ef-core-2.2 entity-framework-core entity-framework-plus

Question

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)

1
0
2/26/2020 6:15:44 PM

Accepted Answer

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()
1
2/27/2020 2:26:58 PM

Popular Answer

This is what i have ended up using. This create 3 sql statements

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


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow