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
You have to initialize the connection directly, as such:
var rootConn = new System.Data.SqlClient.SqlConnection(your_connection_string_minus_your_ef_junk);
Slightly less hacky way:
private static SqlConnection GetConnection()
{
var connStr = ConfigurationManager.ConnectionStrings["ModelContainer"].ConnectionString;
var entityConnStr = new EntityConnectionStringBuilder(connStr);
return new SqlConnection(entityConnStr.ProviderConnectionString);
}
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();
}
}
}
Here is a slightly better performing, but slightly hackier solution to getting the store connection.
public static DbConnection GetStoreConnection<T>() where T : System.Data.Objects.ObjectContext
{
return GetStoreConnection("name=" + typeof(T).Name);
}
public static DbConnection GetStoreConnection(string entityConnectionString)
{
DbConnection storeConnection;
// Let entity framework do the heavy-lifting to create the connection.
using (var connection = new EntityConnection(entityConnectionString))
{
// Steal the connection that EF created.
storeConnection = connection.StoreConnection;
// Make EF forget about the connection that we stole (HACK!)
connection.GetType().GetField("_storeConnection",
BindingFlags.NonPublic | BindingFlags.Instance).SetValue(connection, null);
// Return our shiny, new connection.
return storeConnection;
}
}