为什么Entity Framework在简单地获取表行时会触发两个SQL查询?

时间:2016-04-01 09:05:24

标签: sql-server vb.net entity-framework linq database-performance

我正在使用Entity Framework 6.1.3,当我通过用户名/密码获取用户时,如下所示。 EF实际上向数据库发出两个SQL查询。我使用SQL Server Profiler来检查查询调用。通过阻止第二次调用,我可以减少执行时间。

C#代码:

Dim oSelectedUser As User = (From oUser As User In oDataContainer.Users Where (oUser.UserName = pUserName And oUser.msPassword = pPassword) Select oUser Where oUser.IsActive = True).SingleOrDefault

查询#1:

SELECT TOP (2) 
    [Extent1].[Id] AS [Id], 
    [Extent1].[UserName] AS [UserName], 
    [Extent1].[Password] AS [Password], 
    [Extent1].[Image] AS [Image]
FROM [dbo].[User] AS [Extent1]
WHERE 
    ([Extent1].[UserName] = @p__linq__0) AND ([Extent1].[Password] = @p__linq__1)

查询#2:

exec sp_executesql N'SELECT TOP (2) 
    [Extent1].[Id] AS [Id], 
    [Extent1].[UserName] AS [UserName], 
    [Extent1].[Password] AS [Password], 
    [Extent1].[Image] AS [Image]
    FROM [dbo].[User] AS [Extent1]
    WHERE ([Extent1].[UserName] = @p__linq__0) AND ([Extent1].[Password] = @p__linq__1)',N'@p__linq__0 nvarchar(4000),@p__linq__1 nvarchar(4000)',@p__linq__0=N'usr',@p__linq__1=N'zReNgKelg'

Sql profiler事件:

enter image description here

1 个答案:

答案 0 :(得分:3)

这两个事件基本上向您展示了相同的陈述。 RPC:Completed事件用于整个调用完成时,SP:Stmt用于存储过程中的语句完成时。在这种情况下,它们都是同一个东西。