I\'m building a SQL \"WHERE\" clause dynamically using the System.Linq.Expressions.Expression class. It works well for simple clauses, e.g. to add \"PhaseCode = X\" clause, I do
Calling an extension method, like Enumerable.Any or Queryable.Any, is simply a static method call on the sequence and the lambda expression you created for the WHERE
clause. You can use Expression.Call to do this:
// for Enumerable.Any(IEnumerable,Predicate)
var overload = typeof(Enumerable).GetMethods("Any")
.Single(mi => mi.GetParameters().Count() == 2);
var call = Expression.Call(
overload,
Expression.PropertyOrField(projParam, "GroupsAssigned"),
anyLambda);
For Queryable.Any
, you'll need to roll this up into a method:
static Expression BuildAny(Expression> predicate)
{
var overload = typeof(Queryable).GetMethods("Any")
.Single(mi => mi.GetParameters().Count() == 2);
var call = Expression.Call(
overload,
Expression.PropertyOrField(projParam, "GroupsAssigned"),
predicate);
return call;
}
Although this seems odd that you're unable to do this through a normal query.