实体框架SQL第一个数据库查询

时间:2014-02-27 19:58:02

标签: c# asp.net-mvc entity-framework

我首先使用代码处理ASP.NET MVC应用程序。当我从visual studio内部运行应用程序时(在调试或发布模式下),由于以下自动运行的SQL,我的第一个查询总是较慢:

SELECT Count(*) 
FROM INFORMATION_SCHEMA.TABLES AS t 
WHERE t.TABLE_TYPE = 'BASE TABLE' AND 
(t.TABLE_SCHEMA + '.' + t.TABLE_NAME IN 
('dbo.LoginAttempt','dbo.Product','dbo.Supplier','dbo.AspNetRoles',
'dbo.AspNetUsers','dbo.AspNetUserClaims','dbo.AspNetUserLogins','dbo.AspNetUserRoles') 
OR t.TABLE_NAME = 'EdmMetadata') -- Executing at 2/27/2014 2:43:58 PM -05:00 -- Completed in 20 ms with result: 8 

SELECT [GroupBy1].[A1] AS [C1] FROM ( 
SELECT COUNT(1) AS [A1] 
FROM [dbo].[__MigrationHistory] AS [Extent1] 
) AS [GroupBy1] -- Executing at 2/27/2014 2:43:59 PM -05:00 -- Completed in 3 ms with result: SqlDataReader 

SELECT [GroupBy1].[A1] AS [C1] FROM ( 
SELECT COUNT(1) AS [A1] 
FROM [dbo].[__MigrationHistory] AS [Extent1] 
WHERE ([Extent1].[ContextKey] = @p__linq__0) 
AND (@p__linq__0 IS NOT NULL) ) AS [GroupBy1] -- p__linq__0: 'CompanyName.Migrations.Configuration' (Type = String, Size = 4000) -- Executing at 2/27/2014 2:43:59 PM -05:00 -- Completed in 2 ms with result: SqlDataReader 

SELECT TOP (1) [Project1].[C1] AS [C1], [Project1].[MigrationId] AS [MigrationId], 
[Project1].[Model] AS [Model] FROM ( 
SELECT [Extent1].[MigrationId] AS [MigrationId], 
[Extent1].[Model] AS [Model], 1 AS [C1] 
FROM [dbo].[__MigrationHistory] AS [Extent1] 
WHERE ([Extent1].[ContextKey] = @p__linq__0) 
AND (@p__linq__0 IS NOT NULL) ) AS [Project1] 
ORDER BY [Project1].[MigrationId] DESC -- p__linq__0: 'CompanyName.Migrations.Configuration' (Type = String, Size = 4000) -- Executing at 2/27/2014 2:43:59 PM -05:00 -- Completed in 2 ms with result: SqlDataReader 

我对此SQL有几个问题:

  1. 当我将此应用程序发布到生产环境时,此SQL仍会运行第一个查询吗?
  2. 如果是这样,每个用户的第一个查询会发生这种情况,还是仅在网站上运行第一个查询?
  3. 这些查询是否需要EF才能运行,或者是否有办法禁用它们?

1 个答案:

答案 0 :(得分:3)

除第一个查询外,这是EF检查数据库是否仍然与概念模型(映射的类模型)匹配。如果存在差异,它将尝试将数据库迁移到最新版本。由于您不想在生产中使用迁移,因此可以通过

关闭它
Database.SetInitializer<YourContext>(null);

在初始化中,如果你的应用程序,global.asax.cs在MVC中。

回答你的问题

  1. 是的,它将始终使用第一个查询运行(除非您按上述方式将其关闭)。
  2. 对于应用程序运行的第一个查询,因此当Web应用程序启动时,也会在每次重置应用程序池之后。
  3. 如果您想使用迁移,则必需。