vdefeo
vdefeo

Reputation: 103

LINQ - Dynamic Where Clause on "Query Syntax"

I have been searching about how to make dynamic queries and everything that I found was using "Method Syntax".

Is it possible create dynamic predicates for "Query syntax" ?

I tried to use something like

Expression<Func<TEntity, bool>>

inside the predicate but the compiler return the following message

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

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

It works:

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

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

It doesn't 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 ?

Upvotes: 3

Views: 1324

Answers (2)

Peter Ritchie
Peter Ritchie

Reputation: 35871

Not knowing what you need Expression for, I can't be sure this will do everything you need it to. The use of AsQueryable has me suspect you don't (if you're directly querying a provider, you should already be IQueryable<Localization>); but, you'll have to confirm. But, if you don't need to use Expression, you could 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 a 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 the delegate is executed on the client and not translated into something run on the server (i.e. part of the T-SQL generated by the provider, if that is indeed happening now). If you need that, you'd need to continue using the Expression and continue to use the method chain syntax:

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

I don't believe there's any reason to choose Predicate<T> over Func<T,bool>, other than Predicate<T> is more explicit w.r.t. to intention.

There's also no functional benefit to using query syntax over method chain syntax--just readability/maintainability. I frequently find that to do much in the way of anything complex with providers usually results in dropping down to method chain syntax. I usually just use query syntax with LINQ To Objects.

Upvotes: 1

Servy
Servy

Reputation: 203829

No, you're going to need to use method syntax. There is no way to provide an expression that you have in a variable as the parameter to a method using query syntax.

Upvotes: 0

Related Questions