Mixing raw SQL with IQueryable for dynamic filter

5.9k Views Asked by At

In entity framework 6 is it possible to mix raw SQL generated dynamically with IQueryable like this:

IQueryable<Tree> tree_query = context.Trees.Where(t=>t.Height> 2);
IEnumerable<int> tree_additional_filter = context.Database.SqlQuery<int>("SELECT Id FROM TREE_VIEW WHERE Width < 1");

IQueryable<Tree> final_query = from tree in tree_query 
                               join filtering_tree in tree_additional_filter on filtering_tree.id equals tree.id
                               select tree;

This produces a result as is, but the "tree_additional_filter" is executed in the database in order to construct the final_query. How can I make entity framework construct only one query from this?

I need this to create dynamic filter fields which work together with static ones.

I also tried creating TREE_VIEW entity with only Id column, which I know to always be there. Used System.Linq.Dynamic to construct "where" clause dynamically on a TREE_VIEW entity which has only Id property, but apparently expressions can't be built if properties do not exist in the Type.

2

There are 2 best solutions below

1
On BEST ANSWER

I managed to do it.

  1. Using Dynamic type generation to create a type (NewDynamicType) from fields which I got selecting top 1 from my TREE_VIEW. Attached the NewDynamicType to the db context via DbModelBuilder.RegisterEntityType in OnModelCreating.
  2. With System.Linq.Dynamic then I could construct IQueryable selecting from context.Set(NewDynamicType) any fields the user wants to filter by.
  3. Join into final_query like in my question.

Now my HTML form gets fields from the database view and in each distibution I can have different filters defined without having to write any c#.

1
On

In entity framework 6 is it possible to mix raw SQL generated dynamically with IQueryable like this:

No. Notice that Database.SqlQuery returns an IEnumerable<T>, not an IQueryable<T>. Therefore any additional query expressions will be executed against the query results using LINQ to Objects.

Query Composition with raw SQL queries was introduced in EF Core.