LINQ - Dynamic Where Clause on "Query Syntax"

I was looking for how to do dynamic queries and all I found was to use "Method Syntax".

Is it possible to create dynamic predicates for "Query Syntax"?

I tried using something like

Expression<Func<TEntity, bool>>

inside a predicate, but the compiler returns the following message

"Cannot convert Expression<Func<TEntity, bool>> to bool"

      

it works on Method Syntax "but not on ' Query Syntax

Works:

Expression<Func<Localization, bool>> locClause = (l => l.id == locId);

var results = UnitOfWork.Localization.AsQueryable().Where(locClause).ToList();

      

Does not work:

Expression<Func<Localization, bool>> locClause = (l => l.id == locId);

var result = from l in UnitOfWork.Localization.AsQueryable()
                          where locClause 
                          select l;

      

Is there a way to do this?

+3


source to share


2 answers


Without knowing what you need Expression

, I cannot be sure that this will do everything you need. The usage AsQueryable

will make me suspect that you haven't (if you contact the vendor directly, you should already be IQueryable<Localization>

); but, you will need to confirm. But if you don't need to use Expression

, you can do something like this:

Func<Localization, bool> locClause = (l => l.id == locId);

var result = from l in UnitOfWork.Localization.AsQueryable()
                          where locClause(l)
                          select l;

      

Or with Predicate<T>

:

Predicate<Localization> locClause = l => l.id == locId;

var result = from l in UnitOfWork.Localization.AsQueryable()
                          where locClause(l)
                          select l;

      



This, of course, means that the delegate is being executed on the client and not translated to something running on the server (i.e., part of the T-SQL generated by the vendor, if this is actually happening now). If you need this, you will need to keep using Expression

and keep using the method chaining syntax:

var result = UnitOfWork.Localization.AsQueryable().Where(locClause);

      

I don't believe there is any reason for choosing Predicate<T>

over Func<T,bool>

other Predicate<T>

than a more explicit wrt to intent.

There is also no functional benefit from using query syntax over method chaining syntax - just readability / maintainability. I often find that doing anything tricky with providers usually results in a ditching method chaining syntax. I usually use query syntax with LINQ To Objects.

+1


source


No, you need to use method syntax. It is not possible to provide an expression you have in a variable as a parameter to a method using query syntax.



0


source







All Articles