使用带有EF 4.0和Ninject的mvc-mini-profiler

Joh*_*zen 11 ninject entity-framework-4 asp.net-mvc-3 mvc-mini-profiler

我正在尝试使用基于EF4的应用程序使用新的mvc-mini-profiler,但我不知道如何正确连接到我的目标数据源.

据我所知.

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();
Run Code Online (Sandbox Code Playgroud)

如何在没有contianer的情况下获得与EF容器的连接?我只是新建一个SqlConnection,除了连接字符串包装在所有EF垃圾中.

Ste*_*one 4

稍微不那么hacky的方式:

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


约翰·吉岑 (John Gietzen) 的修正:

所有答案的组合应该适用于实体框架支持的任何后备存储。

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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)