c# - 测量每个 Entity Framework 查询的时间

标签 c# sql-server performance entity-framework entity-framework-6

为了测量和调试 Entity Framework 6.3 中每个查询的时间,我根据 the accepted answer 实现了一个 DbCommandInterceptor相关问题:

public class EFLogger : IDbCommandInterceptor
{
    public void ReaderExecuting(DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext)
    {
        startMeasuring(command, interceptionContext);
    }

    public void ReaderExecuted(DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext)
    {
        stopMeasuring(command, interceptionContext);
    }
    ...
}

DbInterception.Add(new EFLogger());

这很好用,它在每个命令发送到数据库之前和之后被调用,我可以测量它花费的时间。

但是,它只测量 SqlDataReader 初始化之前的时间。 每个查询的大部分时间都花在迭代和使用 SqlDataReader 上。我想知道每个查询需要多长时间,最好不要为每个语句添加秒表代码。

SqlDataReader 关闭或读取“最终”记录时,我能否以某种方式拦截?

我意识到 SqlDataReader 可能并不总是被完全消耗掉,因此最终记录可能很难检测到。目前,我只对 SqlDataReader 迭代到最后的情况感兴趣。

IDbCommandInterceptor 接口(interface)似乎没有为此提供任何事件。

是否有任何其他机制可以捕捉阅读器关闭的时刻?

或者我可以将自定义 DbDataReader 包装器注入(inject)到 Entity Framework 代码中吗?还是 SQL Server 端有替代方法?

最佳答案

您可以将日志输出到控制台 context.Database.Log = Console.Write 参见 https://learn.microsoft.com/en-us/ef/ef6/fundamentals/logging-and-interception获取更多信息。

using (var context = new BlogContext())
{
    context.Database.Log = Console.Write; // set Database.Log property inside dbContex constructor to log all queries
    //your query here
}

这将输出每个已传递参数的查询以及执行查询所花费的时间。

关于c# - 测量每个 Entity Framework 查询的时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58101099/

相关文章:

C#正则表达式匹配字符串末尾的数字

mysql - 将具有相同主键的两个表规范化为 3NF

python - 与 numpy repeat 一起使用的两个数组的逐元素编织

python - 在 Python 中查找数字的所有因数的最有效方法是什么?

c# - 设计一个可变类,在它被使用后变成不可变的

c# - 试图了解如何将变量传递给自定义验证?

sql-server - 子查询返回超过 1 个值。当子查询后面有 =、!=、<、<=、>、>= 或子查询用作表达式时,不允许这样做

c# - WPF 是 100 倍或比普通 Windows 窗体慢的东西是正常的吗?

c# - 无法让 Rhino Mock 迭代 DataReader

sql - 存储过程执行计划 - 数据操作