Entity Framework SQL Debugging
Using Lambdas to Log Generated SQL
Scenario
My boss is a SQL guy, a DBO by trade. Every now and again, he wan't to know what SQL my application is running against the database.
I am not a SQL guy. I've been using EntityFramework and lambdas from nearly the beginning of my .NET adventures. I can read and write SQL...
Solution
Lucky for me, Entity Framework provides a way to log SQL queries made. Now, I don't really care about logging every query in Production, but it's useful to know while I'm debugging an application what queries are being run, when, and how. The following gem I picked up a while back has proved to be extremely useful.
class MyContext : DbContext
{
public MyContext : base(...)
{
// configurations
Database.Log = (query) => { Debug.WriteLine(query); };
}
}
We've used a lambda to tell the database to log operations to the Debugging Output window. The line doesn't even execute in Production, so there won't be a performance.
What I get with this approach, while debugging, is not just the generated query, but also what inputs were used (if any) the time of execution, and the time it took to complete operations.
Conclusion
By using a simple lambda, I've created the ability to quickly see what EntityFramework is doing under the covers without needing to stop my running solution at a breakpoint or delving into the SQL Server tools.
Software Development Nerd