Entity Framework: Using DynamicLinq in a generic filter method

c# dynamic-linq entity-framework generics linq


I am working on a mostly generic application with one Filter method:

IQueryable<T> Filter<T>(IQueryable<T> query, Filter filter) where T : IDataBaseEntity

Here is the filter object being passed in:

    Field: "Header.Title",
    Operator: "contains",
    Value: "asdf"

I have a switch for the operator (contains, <, >, ==, etc) to handle each one differently, but I will just focus on "contains" for this example.

The "query" variable being passed in is a generic list of interfaces, an interface that all 200 of my entities inherit from. I do not even have access to the entity types from this namespace.

In this example, the "query" parameter is an IQueryable of entity "Page". A typical example of DynamicLinq for Contains would be the following:

Expression<Func<Page, bool>> exp = l => l.Contains(filter.Value);
query = query.Where("@0(it)", exp);

However, this part of my application is not strongly typed, my domain doesn't know what a "Page" is, and instead it's using the inherited IDataBaseEntity as the Func<> first type. I get an exception because "No property or field 'Header' exists in type 'IDataBaseEntity'". I tried a variety of other options but ended up with this being the primary issue.

NOTE: I need to keep this an IQueryable and do NOT want to turn it into an IEnumerable at any point for performance reasons. The query is intended to only be run (.AsEnumerable()) after filtering, sorting and paging.

Is it possible to run dynamic linq against IQueryable with an interface type in a namespace that knows nothing about my actual entity types?

7/27/2016 10:25:46 PM

Accepted Answer

How about not using the interface at all - Dynamic Linq is late bound anyway. You can apply the dynamic Where on IQueryable<T> and the result will be IQueryable<T>.

As soon as you can build the string predicate correctly, the following should work:

query = query.Where("Header.Title.Contains(@0)", filter.Value);
7/27/2016 7:53:04 PM

Related Questions

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