Adding LambaExpression to an instance of IQueryable
ParameterExpression parameter = Expression.Parameter(typeof(Product), "x");
MemberExpression Left = Expression.MakeMemberAccess(parameter, typeof(Product).GetProperty("Name"));
ConstantExpression Right = Expression.Constant(value, typeof(String));
BinaryExpression expression = Expression.Eq开发者_运维知识库ual(Left, Right);
LambdaExpression lambada = Expression.Lambda<Func<Product, bool>>(expression, parameter);
Now how do I add this lambada to an instance of an IQuerybale, lets say _query
_query.Where(lambada.Compile());?
I think you just need to change the type of lambda
ParameterExpression parameter = Expression.Parameter(typeof(Product), "x");
MemberExpression Left = Expression.MakeMemberAccess(parameter, typeof(Product).GetProperty("Name"));
ConstantExpression Right = Expression.Constant(value, typeof(String));
BinaryExpression expression = Expression.Equal(Left, Right);
Expression< Func< Product, bool > > lambda = Expression.Lambda<Func<Product, bool>>(expression, parameter);
Now it is an Expression<Func<Product, bool>>
and IQueryable.Where
takes that as an argument. Expression.Lambda<TDelegate>
returns a TDelegate
that is also a LambdaExpression
which is why Expression.Lambda
line compiles in your case and in my case, but IQueryable.Where
wants to see it as an Expression<Func<Product, bool>>
.
Something like:
List< Product > products = new List< Product >
{
new Product { Name = "bar" },
new Product { Name = "foo" }
};
IQueryable< Product > queryable = products.AsQueryable().Where( lambda );
Don't use .Compile
, it would transform the expression into a delegate. An IQueryable
is filtered using an expression, not a delegate :
_query = _query.Where(lambada);
精彩评论