Profiling Entity Framework Code First With MiniProfiler
Updated: thanks, RichardD!
When I tried to find an up to date tutorial on using MiniProfiler with Entity Framework Code First I couldn’t find any that I could use – all either referred old versions of assemblies or didn’t include all information, so here is one.
MiniProfiler presents itself as a “simple but effective mini-profiler for .NET and Ruby”, and indeed it is! Let’s forget about the Ruby part, which I don’t know: it offers an interesting, non-intrusive approach to getting simple performance measures for the execution of ASP.NET MVC action methods and, what interests me more, database calls, such as those produced by EF. Its pluggable nature, however, can potentially lend itself to other uses – more on this on a future post.
MiniProfiler works with MVC only. You need to install it into your project and the best way to do this is through Nuget. You will need three packages: the MiniProfiler itself, the one for MVC 3 (but will work on MVC 4 too) and the one for EF:
Profiling Entity Framework
Now, for setting up Entity Framework profiling, we have three options:
Modify the Web.config file to reference a new provider;
Add code to set up the provider.
In any case, you need to add the following calls to your Application_Start method (or some class called from it):
2: MiniProfiler.Settings.SqlFormatter = new SqlServerFormatter();
Adding the User Interface
In this case, I am using Razor, but you can certainly use ASPX.
After installing the three packages, when you run your application, you will notice a small box on the top upper corner:
One row will show up for each request. For this snapshot, we can tell that we first tried to access some URL, and were redirected to the login page, thus we have one row for the first URL and another for the login page.
If we click on any row we get some MVC-specific performance details of the request, including all of the loaded partial views plus some client-side ones:
When we click Esc, the upper corner box toggles its visibility, so we can forget about it.
As soon as you setup EF profiling, the upper corner box will be basically the same, except if MiniProfiler detects duplicated SQL commands, in which case it will display a !:
And if you click on a row:
Clicking on sql will reveal its details:
Each SQL command that is found to be a duplicate of a previous one will be identified as such.
A great tool indeed, don’t you think? Stay tuned for more!