找出哪些代码运行实体框架 sql 代码 [英] Find out which code run Entity Framework sql code

查看:44
本文介绍了找出哪些代码运行实体框架 sql 代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经开始使用一些实体框架分析器,例如 ANTS 和其他一些类似的替代品.探查器分析后,以实体框架生成的 SQL 查询格式列出所有实体框架瓶颈.但我无法跟踪代码中的查询.是否可以知道哪行代码运行该 SQL 查询?

I have started using some Entity Framework profilers, such as ANTS and some other similar alternatives. After the profiler analyses, it list all the Entity Framework bottlenecks in SQL query format generated by Entity Framework. But I am unable to track which the query in code. Is it possible to know which line of of code runs that SQL query?

推荐答案

我认为你不能让 ANTS 这样做(只有 Redgate 可以).

I don't think you can make ANTS do this (only Redgate can).

但是在分析或不分析时,您始终可以通过将日志记录 Action 附加到上下文的 Database.Log 属性.

But while profiling, or without, you can always log all SQL statements by attaching a logging Action to the context's Database.Log property.

在此日志记录操作中,您还可以记录当时的堆栈跟踪,然后尝试在调试日志记录中查找报告的 SQL 瓶颈:

In this logging action, you can also log the stack trace at that moment and then try to find the reported SQL bottlenecks in the debug logging:

using (var db = new MyContext())
{
    db.Database.Log = s =>
    {
        Debug.WriteLine(s);
        if (s.StartsWith("SELECT"))
            Debug.WriteLine("\nStack trace:\n" +
                string.Join("", new StackTrace(3).GetFrames().ToList()));
    };
    // LINQ statements here.
}

一些评论

  • 我使用 new StackTrace(3) 跳过覆盖日志记录过程本身的前几帧.在堆栈跟踪的某个地方,您会找到触发记录的 SQL 语句的 C# 方法.
  • 这只会记录 SELECT 命令的堆栈跟踪.通常,这些是您想要分析的对象.
  • I use new StackTrace(3) to skip the first few frames that cover the logging process itself. Somewhere down the stack trace you'll find the C# method that fired the logged SQL statement.
  • This only logs a stack trace for SELECT commands. Usually, those are the ones you want to analyze.

从上下文工厂中获取上下文实例是个好主意,这样您只需编写一次此日志记录代码.您可能希望通过 if DEBUG 编译器指令有条件地添加日志记录操作.

It's a good idea to get your context instances from a context factory so you can write this logging code only once. You may want to add the logging action conditionally by an if DEBUG compiler directive.

这篇关于找出哪些代码运行实体框架 sql 代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆