gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 12:37:50 24 4
gpt4 key购买 nike

为了测量和调试 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com