Sunday, February 3, 2013

Using MiniProfiler for Entity Framework

The most important thing to know when using an ORM for your database querying is what exactly happens behind the scene. Do you know if what you are doing will produce acceptable SQL? Do you know if the query will execute fast? Worst of all, do you know how many queries will be executed?

To help answer those questions we need to profile our ORM. Good tools like SQL Profiler, Entity Framework Profiler and NHibernate Profiler exists but you need to spend money for them.

On the free side of things, MiniProfiler is a library we can add to our project via a NuGet package for Entity Framework in this case. MiniProfiler was created for ASP.Net MVC applications in mind but we can still use it in a desktop application using another library called MiniProfiler.Window.

Here is a small example on how to use both libraries together:




This will output to the console the duration of the execution, the raw SQL and parameters of the query. Of course we'll want to refactor this code a bit but it gives you an idea on how MiniProfiler works.

Just a small warning, for reasons unknown to me mixing MiniProfiler and Entity Framework's database initialization like DropCreateDatabaseAlways is not working. As long as we are disabling the initialization with Database.SetInitializer<Context>(null) everything's working just fine.