Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Debug breakpoint when EF executes SQL

When using SQL Server Profiler to trace the SQL queries being executed by the Entity Framework, I see some queries that just shouldn't be being executed and I can't work out which part of the code is the cause!

In Visual Studio Professional 2012, is there a way to set the debugger to break when any SQL query is executed, so I can see the call stack?

like image 673
Connell Avatar asked May 14 '26 08:05

Connell


1 Answers

If you're willing (and allowed) to change the context: yes. You could put this in the context's constructor:

#if DEBUG

    this.Database.Log = s =>
        {
            Debug.WriteLine(s);
        };

#endif

Now you can put a breakpoint on Debug.WriteLine(s); and inspect the stack trace when it's hit.

You can make the breakpoint conditional to see only queries, e.g. by putting s.Contains("[") in the break condition.

like image 152
Gert Arnold Avatar answered May 17 '26 01:05

Gert Arnold



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!