Viewing SQL for Entity Framework 7 Queries

While writing this post on dealing with entity framework and collections I needed a way to see what SQL queries entity framework was sending to the database. At the time I used Express Profiler for the task.

expressProfiler

To get up and running with Express Profiler enter the server and authorization information and click the play button. Each event is logged in the grid. When an event is selected the actual query will show in the panel below the grid. The clear function is also very handy. Just hit it before triggering the entity framework query that you want to see the SQL for to minimize the number of event that have to be gone through.

I came across Express Profiler while watching Julie Lerman’s Looking Ahead to Entity Framework 7 Pluralsight course. This course is one of the ones provided free with a MSDN subscription so there is no reason not to check it. The course is a good introduction to Entity Framework 7. Keep in mind that the course is using beta 4 so things have changed some since it was released.

With the release of ASP.NET 5 Beta 6 a new debug logger was added to log to Visual Studio’s output window. This new logger seemed like it would be useful for logging entity framework queries.

In project.json add a dependency for Microsoft.Framework.Logging.Debug.

In the Configure function of the Startup class use the logger factory to add the new debug logger. This is done via the AddDebug extension method that comes when the new dependency was added above.

Run the application and the output window will contain the SQL that is sent to the database. The downside to this approach is that the log level of verbose outputs a lot of information making it harder to locate the SQL bits.

2 thoughts on “Viewing SQL for Entity Framework 7 Queries”

  1. “The downside to this approach is that the log level of verbose outputs a lot of information making it harder to locate the SQL bits.”

    The AddDebug method has an overload taking a filtering function of type Func. To get just the SQL it seems to work with

    loggerFactory.AddDebug((x,y) => x == “Microsoft.Data.Entity.Query.QueryContextFactory”);

Leave a Reply

Your email address will not be published. Required fields are marked *