0

我有一个现有的控制器操作,如下所示。

Public Function List(ByVal UserID As Integer, Optional ByVa; Filter As String = Nothing) As ActionResult
    Dim records

    If Filter IsNot Nothing Then
        records = context.Contacts.Where(Function(x) x.UserID = UserID and x.Name.Contains(Filter))
    Else
        records = context.Contacts.Where(Function(x) x.UserID = UserID)
    End If

    return View(records)
End Function

我希望使它更简单,如下所示。

Public Function List(ByVal UserID As Integer, Optional ByVa; Filter As String = Nothing) As ActionResult
    Dim records = context.Contacts.Where(Function(x) x.UserID = UserID)

    If Filter IsNot Nothing Then
        records = records.Where(Function(x) x.Name.Contains(Filter))
    End If

    return View(records)
End Function

如果通过了过滤器,EF 是否会触发两个查询,或者它是否足够智能以触发一个查询?

4

2 回答 2

1

试试看!

启动 SQL Management Studio(或类似软件)并加载 SQL Profiler,连接到数据库并查看那里有哪些传入查询。

从理论上讲,EF4 没有理由不能将其作为单个操作运行,因为数据请求直到第二次应用 where 子句之后才会出现。

  • 构建查询
  • 添加 where 子句
  • 添加第二个 where 子句
  • 执行数据检索
于 2012-07-27T10:04:11.673 回答
0

Yes, one query - this is the nature of the IQueryable interface. All methods which return an IQueryable should not execute anything until the IQueryable's enumerator is accessed.

于 2012-07-27T10:08:02.300 回答