Writing Entity Framework generated SQL to Visual Studio output window

Using a powerful ORM like Entity Framework is great. But once in a while when debugging, not having access to the generated SQL can be a real pain.

Fortunately Entity Framework comes with handy logging functionality.

What I do is to wire Entity Framework up for outputting logging information to the output window in Visual Studio like so:

namespace My.Project
{
    public class MyContext : DbContext
    {
        public MyContext(string connection) : base(connection) { }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            #if DEBUG
            Database.Log = s => Debug.Write(s);
            #endif
            
            // Any Fluent API configuration goes here
        }
    }
}

That's it. When debugging your application, all your generated queries will be available for scrutiny in the Visual Studio output window.