Linq to Entities Dynamic Where Where Clause

时间:2014-02-20 16:54:44

标签: vb.net lambda linq-to-entities expression-trees

Dim Param = Expression.Parameter(source.ElementType)
Dim columnProperty = Expression.PropertyOrField(Param, Column.Name)
Dim conversion As Expression = Expression.Convert(columnProperty, GetType(String))
Dim likeValue = Expression.Constant(value, GetType(String))
Dim ContainMethodExp = Expression.[Call](columnProperty, GetType(String).GetMethod("Contains"), likeValue)
Dim where = Expression.[Call](GetType(Queryable), "Where", New Type() {source.ElementType}, source.Expression, Expression.Lambda(ContainMethodExp, Param))

此代码适用于列类型字符串,但它不适用于int32列类型,我尝试使用expression.convert将int32转换为字符串,但它失败了。我能够将成员表达式转换为对象类型,但linq to entities仅支持原始数据类型。

请帮助为Int 32类型编写相同的lambda表达式以进行动态过滤

2 个答案:

答案 0 :(得分:0)

表达式树相当于:

.Where(x => x.Column.Contains(likeValue"))

您希望如何将Contains / LIKE与整数进行比较?!

对于整数,您应该使用Expression.Equal代替Contains方法调用:

Dim Param = Expression.Parameter(source.ElementType)
Dim columnProperty = Expression.PropertyOrField(Param, Column.Name)

Dim equalValue = Integer.Parse(value)

Dim equalValueExpression = Expression.Constant(equalValue, GetType(Integer))
Dim equalExpression = Expression.Equal(columnProperty, equalValueExpression )
Dim where = Expression.[Call](GetType(Queryable), "Where", New Type() {source.ElementType}, source.Expression, Expression.Lambda(equalExpression , Param))

我没有测试过,但应该可以使用。

答案 1 :(得分:0)

MarcinJuraszek回答作品,但我发现另一个链接也帮我解决了问题

访问How to Type Cast dynamically to string while using Contains in Dynamic LINQ?

另一种解决方案是使用String函数的StringConvert,以便您可以使用contains

    Dim method As MethodInfo = GetType(String).GetMethod("Contains", New Type() {GetType(String)})
    Dim Value As Expression = Expression.Convert(searchFilter, GetType(String))
    Dim Param = Expression.Parameter(source.ElementType)
    Dim columnProperty As Expression = Expression.Property(Param, Column.Name)
    columnProperty = Expression.Convert(columnProperty, GetType(System.Nullable(Of Double)))
    Dim stringConvertMethod = GetType(SqlFunctions).GetMethod("StringConvert", New Type() {GetType(System.Nullable(Of Double))})
    columnProperty = Expression.[Call](stringConvertMethod, columnProperty)
    Dim containsMethodExp = Expression.Call(columnProperty, method, Value)
    Dim likeValue = Expression.Constant(value, GetType(String))
    Dim ContainMethodExp = Expression.[Call](columnProperty, GetType(String).GetMethod("Contains"), likeValue)
    Dim where = Expression.[Call](GetType(Queryable), "Where", New Type() {source.ElementType}, source.Expression, Expression.Lambda(ContainMethodExp, Param))