我将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);
}
所以我的questin是为什么生成的sql是Select Top(2)
答案 0 :(得分:4)
执行Select Top (2)
因为DBSet在内部SingleOrDefault()
(请参阅here方法FindInStore
)使用Find
方法来执行查询。
这可以确保,如果返回2个结果,则抛出异常,因为SingleOrDefault定义它只需要一个结果或没有结果。
Select Top (1)
生成为您使用FirstOrDefault()的Sql。