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);
LambdaExpression lambada = Expression.Lambda<Func<Product, bool>>(expression, parameter);现在,假设是_query,我该如何将这个lambada添加到一个IQuerybale实例中
_query.Where(lambada.Compile());?
发布于 2010-03-17 16:31:49
我认为您只需要更改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);现在它是一个Expression<Func<Product, bool>>,IQueryable.Where将其作为参数。Expression.Lambda<TDelegate>返回一个TDelegate,它也是一个LambdaExpression,这就是为什么在你的例子和我的例子中Expression.Lambda行被编译,但是IQueryable.Where想把它看作一个Expression<Func<Product, bool>>。
类似于:
List< Product > products = new List< Product >
{
new Product { Name = "bar" },
new Product { Name = "foo" }
};
IQueryable< Product > queryable = products.AsQueryable().Where( lambda );发布于 2010-03-17 16:20:48
不要使用.Compile,它会将表达式转换为委托。IQueryable是使用表达式过滤的,而不是委托:
_query = _query.Where(lambada);https://stackoverflow.com/questions/2460701
复制相似问题