2014-02-20 96 views
0
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到实体仅支持原始数据类型。LINQ到实体动态Where子句

请帮忙写关于INT 32型动态过滤相同的lambda表达式

回答

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)) 

我没有测试过这一点,但应该工作。

+0

这是我的错误,在发布问题时我没有将“Contains”更改为“Equals”。它正在工作,谢谢。 – tinku99

+1

我试图将整数类型转换为字符串类型,并且使用contains thod为字符串类型。我尝试了int类型的equals方法,但它不起作用。无论如何,你给我的代码工作...谢谢你。 – tinku99

0

MarcinJuraszek答案的作品,但我发现了另一个链接,还帮我解决这个问题

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

另一种解决方案是使用SQL函数StringConvert,这样就可以使用包含

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))