1

我試圖做一個擴展方法,它接受一個表達式指向一個實體的屬性,以及一個常量字符串來比較它使用String.Contains,它首先檢查字符串是空或空,並且僅在字符串具有值時應用過濾器。這是我在表達樹中的第一次嘗試,所以我不確定發生了什麼,現在我有一個例外,我不知道如何治療...在Linq的表達式樹到實體

我在這個目前爲止:

<System.Runtime.CompilerServices.Extension()> 
    Public Function CheckAndFilter(Of T)(source As System.Linq.IQueryable(Of T), expressionField As System.Linq.Expressions.Expression(Of System.Func(Of T, String)), compareTo As String) As IQueryable(Of T) 


     If String.IsNullOrEmpty(compareTo) Then 
      Return source 
     Else 
      Dim memberExp As Expressions.MemberExpression = DirectCast(expressionField.Body, Expressions.MemberExpression) 

      Dim param = Expressions.Expression.Parameter(GetType(T)) 
      Dim method As Reflection.MethodInfo = GetType(String).GetMethod("Contains") 

      Dim compareToExpression = Expressions.Expression.Constant(compareTo) 
      Dim finalExpr = Expressions.Expression.Call(memberExp, method, compareToExpression) 

      Dim lambda = Expressions.Expression.Lambda(Of Func(Of T, Boolean))(finalExpr, param) 
      Return source.Where(lambda) 
     End If 
    End Function 

我打電話是這樣,對一個DbContext在那裏我有一個Customer實體與FirstName字符串屬性:

Dim results = repository.Customers.CheckAndFilter(Function(c) c.FirstName, searchText) 

,異常爲:

{"The parameter 'c' was not bound in the specified LINQ to Entities query expression."} 

有什麼想法?

回答

2

哈哈!

這是因爲我已經宣佈了新的參數,而不是重新使用一個通過表達傳遞...

<System.Runtime.CompilerServices.Extension()> 
Public Function CheckAndFilter(Of T)(source As System.Linq.IQueryable(Of T), expressionField As System.Linq.Expressions.Expression(Of System.Func(Of T, String)), compareTo As String) As IQueryable(Of T) 


    If String.IsNullOrEmpty(compareTo) Then 
     Return source 
    Else 
     Dim memberExp As Expressions.MemberExpression = DirectCast(expressionField.Body, Expressions.MemberExpression) 

     Dim method As Reflection.MethodInfo = GetType(String).GetMethod("Contains") 

     Dim compareToExpression = Expressions.Expression.Constant(compareTo) 
     Dim finalExpr = Expressions.Expression.Call(memberExp, method, compareToExpression) 

     Dim lambda = Expressions.Expression.Lambda(Of Func(Of T, Boolean))(finalExpr, expressionField.Parameters) 
     Return source.Where(lambda) 
    End If 
End Function