Keeping Track of SQL Statements in an Entity Framework Code First Project

One of the more annoying omissions from the Microsoft Entity Framework is the out of the box ability to easily trace the SQL statements produced by the framework. In the past we’ve got around that using Community Entity Framework Provider Wrappers which includes EFTracingProvider that can log the generated SQL statements to the console or to a file.

However in our most recent project where we are trying Code First, it runs into a bit of a problem as the EFTracingProvider uses the ObjectContext whereas Code First is based on the newer DBContext. A trawl around the Internet can find various posts about how to get the providers to work this post being probably the most complete example. The big issue though is that they all require some degree of extra code to con the provider into working with the DBContext, and they all ran into various issues with our Code First solution, most often related to the parts where the solution generated the initial SQLServer Compact database.

However with some more digging I came across a solution in the form of the Clutch Diagnostics EntityFramework package on Nuget. The package wraps up another project, the excellent (and free) MiniProfiler which whilst it is designed for use in web projects is adaptable enough to be used in other ways. The Clutch Diagnostics EntityFramework only needs a couple of additional lines in the start up code for the application, and then an implementation of IDBTracingListener to send the traces somewhere. There are several of these available, but for our purposes it was really easy to write our own. The big advantage is that there is no need to make any changes to the DBContext, so the code can be easily and automatically removed for releases.

For an example of how to implement IDBTracingListener, check out my answer on Stack Overflow.

Leave a Reply