2

I have a relatively simple LINQ expression which I need to convert into VB expression tree syntax. This is likely an easy task for folks that are familiar, but I am new to the realm of LINQ expression trees.

In my samples, you see a "New Int16() {}" array. That value must be parameterized at run-time with an array of values from another code element.

my query is:

from i in tblInstitutions
let ChildHasCategory = i.tblInstCtgyHistories.Where(Function(CtgyHist) CtgyHist.EndDate is Nothing AND ( (New Int16() {32,35,38,34}).Contains(CtgyHist.InstCtgyCodeFK)))
where ChildHasCategory.Any()
select i

Which can also be represented as:

tblInstitutions
.Select (i => new  {
        i = i, 
        ChildHasCategory = (IEnumerable<tblInstCtgyHistory>)(i.tblInstCtgyHistories)
           .Where (
              CtgyHist => 
                    ((CtgyHist.EndDate == null) & 
                       (IEnumerable<Int16>)(new Int16[] { 32, 35, 38, 34 } ).Contains (CtgyHist.InstCtgyCodeFK)
                    )
           )
     }
)
.Where ($VB$It => $VB$It.ChildHasCategory.Any ())
.Select ($VB$It => $VB$It.i)

This is going to be used in the context of a custom filter in an ASP.NET Dynamic Data web application. I'd like to mimic the default approach. A sample of one of the other dynamic filter code-behind is:

Public Overrides Function GetQueryable(source As IQueryable) As IQueryable
    Dim value = TextBox1.Text
    If String.IsNullOrWhiteSpace(value) Then
        Return source
    End If

    If DefaultValues IsNot Nothing Then
        DefaultValues(Column.Name) = value
    End If

    Dim parameter = Expression.Parameter(source.ElementType)
    Dim columnProperty = Expression.PropertyOrField(parameter, Column.Name)
    Dim likeValue = Expression.Constant(value, GetType(String))
    Dim condition = Expression.Call(columnProperty, GetType(String).GetMethod("Contains"), likeValue)
    Dim where = Expression.Call(GetType(Queryable), "Where", New Type() {source.ElementType}, source.Expression, Expression.Lambda(condition, parameter))
    Return source.Provider.CreateQuery(where)
End Function
4

1 回答 1

2

我不确定您是否真的需要在这里担心表达式树。首先,我们应该能够如下表达您的查询:

Dim targetCodes = new Int16() {32, 35, 38, 34 } ' This could be data driven as well
return from i in tblInstitutions
       where i.tblInstCtgyHistories.Any(Function(ctgyHist) ctgyHist.EndDate is Nothing AndAlso 
              targetCodes.Contains(ctgyHist.InstCtgyCodeFK))
       select i

鉴于此,在什么情况下您需要自定义表达式树?

于 2013-04-03T19:47:49.767 回答