Find out which code run Entity Framework sql code

379 views Asked by At

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?

1

There are 1 answers

1
Gert Arnold On

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

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

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.
}

Some comments

  • 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.

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.