Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using mvc-mini-profiler with EF 4.0 and Ninject

I'm trying to use the new mvc-mini-profiler with my EF4 based app, but I have no idea how to properly get a connection to my destination datasource.

Here's as far as I have gotten.

Func<IMyContainer> createContainer = () =>
{
    var profiler = MiniProfiler.Current;

    if (profiler != null)
    {
        var rootConn = // ????
        var conn = ProfiledDbConnection.Get(rootConn);
        return ObjectContextUtils.CreateObjectContext<MyContainer>(conn);
    }
    else
    {
        return new MyContainer();
    }
};

kernel.Bind<IMyContainer>().ToMethod(ctx => createContainer()).InRequestScope();

How do I get a connection to an EF container, without the contianer itself? I would just new-up a SqlConnection, except that the connection string is wrapped in all of the EF junk.

like image 824
John Gietzen Avatar asked Jun 09 '11 16:06

John Gietzen


1 Answers

Slightly less hacky way:

private static SqlConnection GetConnection()
{
    var connStr = ConfigurationManager.ConnectionStrings["ModelContainer"].ConnectionString;
    var entityConnStr = new EntityConnectionStringBuilder(connStr);
    return new SqlConnection(entityConnStr.ProviderConnectionString);
}


Amendment by John Gietzen:

This combination of all of the answers should work for ANY backing store that Entity Framework supports.

public static DbConnection GetStoreConnection<T>() where T : System.Data.Objects.ObjectContext
{
    return GetStoreConnection("name=" + typeof(T).Name);
}

public static DbConnection GetStoreConnection(string entityConnectionString)
{
    // Build the initial connection string.
    var builder = new EntityConnectionStringBuilder(entityConnectionString);

    // If the initial connection string refers to an entry in the configuration, load that as the builder.
    object configName;
    if (builder.TryGetValue("name", out configName))
    {
        var configEntry = WebConfigurationManager.ConnectionStrings[configName.ToString()];
        builder = new EntityConnectionStringBuilder(configEntry.ConnectionString);
    }

    // Find the proper factory for the underlying connection.
    var factory = DbProviderFactories.GetFactory(builder.Provider);

    // Build the new connection.
    DbConnection tempConnection = null;
    try
    {
        tempConnection = factory.CreateConnection();
        tempConnection.ConnectionString = builder.ProviderConnectionString;

        var connection = tempConnection;
        tempConnection = null;
        return connection;
    }
    finally
    {
        // If creating of the connection failed, dispose the connection.
        if (tempConnection != null)
        {
            tempConnection.Dispose();
        }
    }
}
like image 106
Steve Johnstone Avatar answered Sep 28 '22 02:09

Steve Johnstone