Quantcast
Channel: Development With A Dot
Viewing all articles
Browse latest Browse all 404

Profiling Entity Framework Code First With MiniProfiler

$
0
0

Updated: thanks, RichardD!

Introduction

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.

Installation

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:

image

image

image

The Nuget packages will add the required assemblies, add a sample Razor layout view that demonstrates how to include the required JavaScript code and will add a class with a method that will fire when the web application starts (courtesy of PreApplicationStartMethodAttribute) and register a new module dynamically (thanks to WebActivator). This will setup a global filter and will replace all of the registered view engines with a profiling wrapper of them.

After installing the three packages, when you run your application, you will notice a small box on the top upper corner:

image

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:

image

When we click Esc, the upper corner box toggles its visibility, so we can forget about it.

Profiling Entity Framework

Now, for setting up Entity Framework profiling, we have three options:

  1. Change the DbContext class;
  2. Modify the Web.config file to reference a new provider;
  3. 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):

   1: MiniProfilerEF.Initialize();
   2: MiniProfiler.Settings.SqlFormatter = new SqlServerFormatter();

As RichardD warned me, that's all it takes, no need to follow the next steps, these were only required for old versions.

Changing the Context

The first approach consists on changing your DbContext class so that it calls the base constructor that takes a connection, and we make sure we wrap the native connection in a profiling connection. The code might look like this:

   1:publicclass SomeContext : DbContext
   2: {
   3:public SomeContext() : base(GetProfilerConnection(), true)
   4:     {
   5:     }
   6:  
   7:privatestatic DbConnection GetProfilerConnection()
   8:     {
   9:returnnew EFProfiledDbConnection(new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionName"].ConnectionString), MiniProfiler.Current);
  10:     }
  11:  
  12://...
  13: }

That’s all you need. Of course, if you have multiple context, you will need to change all, or, better still, have a base class.

Setting a Provider Factory By Configuration

The second approach consists of registering a provider factory on the Web.config file. This makes usage of the ADO.NET provider mechanism. All you have to do is add these lines:

   1:<system.data>
   2:<DbProviderFactories>
   3:<addname="StackExchange.Profiling.Data.ProfiledDbProviderFactory"invariant="StackExchange.Profiling.Data.ProfiledDbProviderFactory"description="StackExchange.Profiling.Data.ProfiledDbProviderFactory"type="StackExchange.Profiling.Data.ProfiledDbProviderFactory, MiniProfiler, Version=2.1.0.0, Culture=neutral, PublicKeyToken=b44f9351044011a3" /-->
   4:</DbProviderFactories>
   5:</system.data>

This will apply to all contexts, so you don’t need to change them.

Setting a Provider Factory By Code

The final approach is strictly code-based and will also apply to all contexts:

   1: Database.DefaultConnectionFactory = new ProfiledDbConnectionFactory(new SqlConnectionFactory(ConfigurationManager.ConnectionStrings["ConnectionName"].ConnectionString));

Conclusion

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 !:

image

And if you click on a row:

image

Clicking on sql will reveal its details:

image

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!


Viewing all articles
Browse latest Browse all 404

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>