Linq To Entities中的表达式树

时间:2012-03-02 10:15:05

标签: linq entity-framework lambda linq-to-entities linq-expressions

我正在尝试创建一个扩展方法,它接受一个指向实体上的属性的表达式,以及一个常量字符串,用于将其与使用String.Contains进行比较,首先检查该字符串是否为null或为空,仅在字符串具有值时应用过滤器。这是我在表达树中的第一次涉猎,所以我不确定发生了什么,现在我有一个例外,我不知道如何治愈......

我到目前为止:

<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."}

有什么想法吗?

1 个答案:

答案 0 :(得分: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