当究竟实体框架消防SQL命令?(When exactly does Entity Framework

2019-09-26 06:52发布

假设我有类似的代码:

public void TestWhenSqlFires()
{
    var db = new Db(); // EF DbContext
    var items = db.SimpleObjects; // SimpleObject implements interface IId
    var byId = WhereId(items, 1);
    var array = byId.ToArray();
}

protected IEnumerable<IId> WhereId(IEnumerable<IId> items, int id)
{
    return items.Where(i => i.Id == id);
}

在TestWhenSqlFires哪一行()将SQL实际上对数据库运行?

(这是从意见中剥离出来的一个问题这个答案 )

Answer 1:

一个办法,找出并测试自己:

打开SQL Server Management Studio中,打开一个新的查询,选择EF将针对运行数据库,并运行此查询:

SELECT top 10 deqs.last_execution_time AS [Time], dest.TEXT AS [Query]
FROM sys.dm_exec_query_stats AS deqs
CROSS APPLY sys.dm_exec_sql_text(deqs.sql_handle) AS dest
ORDER BY deqs.last_execution_time DESC

这告诉你已经对数据库运行在过去的10个查询。

在TestWhenSqlFires()的第一行设置一个断点,运行代码,然后运行跨过每行后上面的查询。 你会找到:

// C# Line 1
var db = new Db();

--SQL Line 1
SELECT TABLE_SCHEMA SchemaName, TABLE_NAME Name FROM INFORMATION_SCHEMA.TABLES
    WHERE TABLE_TYPE = 'BASE TABLE'

// C# Line 2
var items = db.SimpleObjects;

--SQL Line 2
SELECT COUNT(*) FROM [sys].[databases] WHERE [name]=@1

SELECT [GroupBy1].[A1] AS [C1] FROM (
    SELECT COUNT(1) AS [A1] FROM [dbo].[__MigrationHistory] AS [Extent1]
) AS [GroupBy1]

(@1 nvarchar(4000))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]
     )  AS [Project1]  ORDER BY [Project1].[MigrationId] DESC

// C# Line 3
var byId = WhereId(items, 1);

--SQL Line 3

// C# Line 4
var array = byId.ToArray();

--SQL Line 4
SELECT [Extent1].[Id] AS [Id], [Extent1].[Stuff] AS [Stuff]
    FROM [dbo].[SimpleObject] AS [Extent1]

最终的SQL查询EF实际获取数据。 现有的查询只是它热身 - 验证数据库中存在,它是一个使用EF5迁移历史,以及它目前的迁移历史散列相匹配。

所以答案是- 4号线,之后.ToArray()被调用(或枚举集,像.ToList()的foreach等任何呼叫)。 值得注意的是它传递给接受IEnumerable的方法,即使有一个特定的通用参与,不枚举集合,因此不会断火SQL高于所需的更早。



文章来源: When exactly does Entity Framework Fire a SQL Command?