0

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
  • you can log all your Linq (SQL GENERATED) query in your code..by logging them in a file Commented Jan 1, 2017 at 11:59

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Should be accepted as answer. Btw I used the constructor of StackTrace as new StackTrace(3, true) to see file information in the log according to this question

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.