【问题标题】:EF 5 Find profilerEF 5 查找分析器
【发布时间】:2012-10-03 05:26:33
【问题描述】:

我将 EF 5 用于我的项目并使用 EntityProfiler 对其进行分析,我看到当我使用 Find 进行查询时生成的 sql 是:

SELECT TOP (2) [Extent1].[ID]                  AS [ID],
               [Extent1].[TargetID]            AS [TargetID],
               [Extent1].[BranchID]            AS [BranchID],
               [Extent1].[ApplicationStatus]   AS [ApplicationStatus],
               [Extent1].[UserID]              AS [UserID],
               [Extent1].[AssignedOfficer]     AS [AssignedOfficer],
               [Extent1].[AssignedOfficerCRM]  AS [AssignedOfficerCRM],
               [Extent1].[RegistrationDate]    AS [RegistrationDate],
               [Extent1].[DecisionReasons]     AS [DecisionReasons],
               [Extent1].[DecisionExceptionID] AS [DecisionExceptionID],
               [Extent1].[RiskComment]         AS [RiskComment],
               [Extent1].[CESInformed]         AS [CESInformed],
               [Extent1].[IsCommited]          AS [IsCommited]
FROM   [dbo].[Applications] AS [Extent1]
WHERE  [Extent1].[ID] = '900100' /* @p0 */

被调用的代码是:

 public T GetByID(object primaryKey)
        {
            return DB.Set<T>().Find(primaryKey);
        }

所以我的问题是为什么在生成的 sql 中是 Select Top (2)

【问题讨论】:

    标签: c# sql ef-code-first entity-framework-5


    【解决方案1】:

    它执行Select Top (2),因为DBSet 在内部使用SingleOrDefault()(参见here 方法FindInStore)来执行Find 方法来执行查询。

    这样可以确保,如果返回 2 个结果,则会引发异常,因为 SingleOrDefault 定义它只期望一个结果或什么都不期望。

    Select Top (1) 生成为 Sql wenn,您使用 FirstOrDefault()。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-07
      • 1970-01-01
      相关资源
      最近更新 更多