Search code examples
entity-frameworkasp.net-mvc-3ado.netmvc-mini-profiler

MVCminiProfiler db profiler, how to get dbConnection with the entity framework


I'm trying to integrate the MVC-mini-Profiler into my mvc project to help profile the data calls. I'm using the Entity Framework 4.1. In the Profiler documentation is says use:

var conn = ProfiledDbConnection.Get(GetConnection());

The GetConnection() needs to return a System.Data.Common.DbConnection. Does anyone know how to get the System.Data.Common.DbConnection from the current context?

http://code.google.com/p/mvc-mini-profiler/


Solution

  • You have 2 options:

    If you already have the EF Container created, you can do this:

    var conn = (SqlConnection)((EntityConnection)efContainer.Connection).StoreConnection
    

    If you are going to create EF container using a new connection, you can create a new connection using EF connection string like so:

    var connectionString = new EntityConnectionStringBuilder(ConfigurationManager.ConnectionStrings["EFConnectionString"].ConnectionString);
    DbConnection con = new SqlConnection(connectionString.ProviderConnectionString);
    con = ProfiledDbConnection.Get(con);
    return ObjectContextUtils.CreateObjectContext<EFContainer>(con);