gpt4 book ai didi

asp.net-mvc-3 - 将 mvc-mini-profiler 与 EF 4.0 和 Ninject 结合使用

转载 作者:行者123 更新时间:2023-12-03 02:37:12 25 4
gpt4 key购买 nike

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

这就是我所了解到的。

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();

如何在没有容器本身的情况下获得与 EF 容器的连接?我只是新建一个 SqlConnection,只不过连接字符串包含在所有 EF 垃圾中。

最佳答案

稍微不那么hacky的方式:

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

<小时/> 约翰·吉岑 (John Gietzen) 修正:

所有答案的组合应该适用于 Entity Framework 支持的任何后备存储。

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();
}
}
}

关于asp.net-mvc-3 - 将 mvc-mini-profiler 与 EF 4.0 和 Ninject 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6296444/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com