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?
Asked
Active
Viewed 351 times
0
-
you can log all your Linq (SQL GENERATED) query in your code..by logging them in a file – federico scamuzzi Jan 01 '17 at 11:59
1 Answers
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.

Gert Arnold
- 105,341
- 31
- 202
- 291
-
1Should 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](https://stackoverflow.com/questions/1650253/stacktrace-filename-unknown) – Perrier Aug 30 '18 at 08:30