Add where where in the Include statement for the Queryable

Suppose I have the following two tables

  • A
  • IN
  • WITH

Tables A, B, and C have a logical column called "IsEnabled".

Between the tables there is a ratio from 1 to several:

  • A-> B
  • B-> C

I am using the Entity framework to query a table, and programming in C #. Suppose I need all the columns in A, I do the following:

var query = _context.A; query.where( <where clause> )

If I need to include columns B to prevent lazy loading,

 query.Include ( s => sB ); 

The question is, how to include B columns by adding a where clause to select only rows with IsEnabled = 1? I am looking for something like:

query.Include ( s => sBwhere ( k => k.IsEnabled = 1 )) (This does not work and throws an exception at runtime)

If we can get the above question, I want to include C columns too rows that IsEnabled = 1 for B and C. Is this possible?

+5
source share
2 answers

Include is used to reliably load relationships, but, unfortunately, the Entity Framework does not support filtering these collections on the server side, either with lazy or high load.

You have two options: do client-side filtering or rebuild your queries to use them most efficiently (for example, if you're after C, select C.Where(c => c.IsEnabled && cBIsEnabled && cBAIsEnabled) ).

+1
source

Suppose you have an object similar to this

 public class A { public int Id {get;set;} public ICollection<B> Bs {get;set;} } public class B { public bool IsEnabled {get;set;} } 

Therefore, when you execute the request, since you have ICollection in Bs , it should work without runtime errors.

0
source

Source: https://habr.com/ru/post/1244853/


All Articles