for future reference - final code in vb.net
predicate extension
Imports SD.LLBLGen.Pro.LinqSupportClasses.ExpressionHandlers
Imports System.Runtime.CompilerServices
Imports System.Linq.Expressions
Imports LinqExpression = System.Linq.Expressions.Expression
Public Module LLBLGenPredicateBuilder
Public Function Null(Of T)() As System.Linq.Expressions.Expression(Of Func(Of T, Boolean))
Return Nothing
End Function
Public Function CreateFromToReplaceSet(from As IList(Of ParameterExpression), [to] As IList(Of ParameterExpression)) As Dictionary(Of LinqExpression, LinqExpression)
Dim toReturn As New Dictionary(Of LinqExpression, LinqExpression)()
For i As Integer = 0 To from.Count - 1
toReturn.Add(from(i), [to](i))
Next
Return toReturn
End Function
<Extension()>
Public Function [Or](Of T)(expr1 As System.Linq.Expressions.Expression(Of Func(Of T, Boolean)), expr2 As System.Linq.Expressions.Expression(Of Func(Of T, Boolean))) As System.Linq.Expressions.Expression(Of Func(Of T, Boolean))
If expr1 Is Nothing Then Return expr2
Dim replacer As New ExpressionReplacer(CreateFromToReplaceSet(expr2.Parameters, expr1.Parameters), Nothing, Nothing, Nothing, Nothing)
Dim rightExpression As LambdaExpression = DirectCast(replacer.HandleExpression(expr2), LambdaExpression)
Return System.Linq.Expressions.Expression.Lambda(Of Func(Of T, Boolean))(System.Linq.Expressions.Expression.[OrElse](expr1.Body, rightExpression.Body), expr1.Parameters)
End Function
<Extension()>
Public Function [And](Of T)(expr1 As System.Linq.Expressions.Expression(Of Func(Of T, Boolean)), expr2 As System.Linq.Expressions.Expression(Of Func(Of T, Boolean))) As System.Linq.Expressions.Expression(Of Func(Of T, Boolean))
If expr1 Is Nothing Then Return expr2
Dim replacer As New ExpressionReplacer(CreateFromToReplaceSet(expr2.Parameters, expr1.Parameters), Nothing, Nothing, Nothing, Nothing)
Dim rightExpression As LambdaExpression = DirectCast(replacer.HandleExpression(expr2), LambdaExpression)
Return System.Linq.Expressions.Expression.Lambda(Of Func(Of T, Boolean))(System.Linq.Expressions.Expression.[AndAlso](expr1.Body, rightExpression.Body), expr1.Parameters)
End Function
End Module
code useage
Dim lmd As New Linq.LinqMetaData()
Dim linq As IQueryable(Of VwCrsCustomerEntity)
linq = From cus In lmd.VwCrsCustomer
'BranchSecurity
If LoggedInSysUser.BranchRestrictions.Count > 0 Then
'Below code only finds exact matches
' linq = From cus In linq Where LoggedInSysUser.BranchRestrictions.Contains(cus.Branch)
'Predicate expression builder finds any customers containing location name in associated branch
Dim predicate = LLBLGenPredicateBuilder.Null(Of VwCrsCustomerEntity)()
For Each i As String In LoggedInSysUser.BranchRestrictions
Dim _branch = i 'Very Important
predicate = predicate.Or(Function(x) x.Branch.Contains(_branch))
Next
linq = linq.Where(predicate)
End If