LInq to Entities中的条件Where子句返回所有列

时间:2010-11-16 22:14:30

标签: asp.net linq entity-framework

我在linq中使用条件where where子句,如下所示

    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

然而,当我通过

查看生成的sql时
Debug.Print(DirectCast(q, System.Data.Objects.ObjectQuery(Of Product)).ToTraceString)

生成的sql显示,当我需要返回的是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]

无论如何强制EF只选择我指定的列但是在Product类所需的任何属性上保留条件where子句吗?

1 个答案:

答案 0 :(得分:0)

您可以动态创建Where子句作为表达式,然后在从Linq上下文中选择数据的同时应用表达式。

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