tags:

views:

44

answers:

2

Hi,

I am attempting to create a dynamic where clause using the standard expression API.

var query = (
            from p in Parties
                orderby p.PartyId
                orderby p.FullName
                select p
).AsQueryable();


 Expression<Func<Party, bool>> @fn = (p) => SqlMethods.Like(p.FullName, "%smith%") || SqlMethods.Like(p.Person.FirstName, "%smith%");
 Expression<Func<Party, bool>> @sn = (p) => SqlMethods.Like(p.Person.FirstName, words[0]);

 ParameterExpression pe = Expression.Parameter(typeof(Party), "p");
 Expression orelse = Expression.OrElse(
  Expression.Lambda(@fn, pe),
  Expression.Lambda(@sn, pe)
 );

The expressions above will ultimately be added to a where clause. I need to add a bunch of 'likes'.

How do I do this?

I get InvalidOperationException on the operator OrElse I have also tried Expression.Or

Thanks

Regards

Craig.

A: 

Calling Expression.Lambda() is redundant as Expression<T> already derives from LambdaExpression. However, you have to instead call Expression.Invoke() on your lambdas to "close" them with respect to your actual parameter. Try something like the following:

 ParameterExpression pe = Expression.Parameter(typeof(Party), "p"); 
 Expression orelse = Expression.OrElse( 
  Expression.Invoke(@fn, pe), 
  Expression.Invoke(@sn, pe) 
 ); 

You will ultimately need to create a LambdaExpression from your expression, so:

var myLambda = (Expression<Func<Party, bool>>)Expression.Lambda(orElse, pe);

Then you can use it against your queryable:

var result = Parties.Where(myLambda);
luksan
+1  A: 

Have you checked out PredicateBuilder?

http://www.albahari.com/nutshell/predicatebuilder.aspx

It can make dynamically creating expressions for where clauses much easier.

Mant101