开发者

Conditional Where clauses in LInq to Entities returns all columns

I am using conditional where clauses in linq to entities as below

    Dim q = (From x In ctx.Product)

    If mySearchField = SearchField.ProductId Then
       q = q.Where(Function(y) y.ProductId = mySearchTerm)
    ElseIf s.SearchField = SearchField.ProductCode Then
       q = q.Where(Function(y) y.ProductCode = mySearchTerm)
    ElseIf s.SearchField = SearchField.ProductName Then
       q = q.Where(Function(y) y.ProductName = mySearchTerm)
    End If

Dim productIds As List(Of Integer) = (From x In q Select x.ProductId).ToList

However when i view the generated sql via

Debug.Print(DirectCast(q, System.Data.Objects.ObjectQuery(Of Product)).ToTraceString)

The generated sql shows that it selects all three columns of the product class when all I need to return is ProductId.

SELECT 
[Extent1].[ProductId] AS [ProductId], 
[Extent1].[ProductCode] AS [ProductCode], 
[Extent1].[ProductName] AS [ProductName]
FROM (SELECT 
      [Product].[ProductId] AS [ProductId], 
      [Product].[ProductCode] AS [ProductCode], 
      [Product].[ProductName] AS [ProductName]
      FROM [dbo].[Product] AS [Product]) AS [Extent1]

Is there anyway of forcing EF to only select the columns I specify but keep the conditional whe开发者_运维问答re clauses on any property I need on the Product class?


You can create your Where clause dynamically as an Expression, and then apply the expression at the same time as you select the data from the Linq Context.

Dim MyWhereExpr As Expression(Of Func(Of Product, Bool))
MyWhereExpr = Function(y) True

If ... Then
    MyWhereExpr = Function(y) y.ProductId = mySearchTerm
ElseIf ...

Dim productIds As List(Of Integer) = _
    ctx.Product.Where(MyWhereExpr).Select(Function(y) y.ProductId).ToList
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜