使用MVC-迷你探查与EF 4.0和Ninject [英] Using mvc-mini-profiler with EF 4.0 and Ninject
本文介绍了使用MVC-迷你探查与EF 4.0和Ninject的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图使用新的MVC-迷你探查与我的基于EF4应用程序,但我不知道如何正确地到达我的目的地数据源的连接。
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();
我如何得到一个EF容器的连接,而不contianer本身呢?我只想新的向上一个SqlConnection,除了连接字符串被包裹在所有的EF垃圾。
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.
推荐答案
略少于哈克方式:
private static SqlConnection GetConnection()
{
var connStr = ConfigurationManager.ConnectionStrings["ModelContainer"].ConnectionString;
var entityConnStr = new EntityConnectionStringBuilder(connStr);
return new SqlConnection(entityConnStr.ProviderConnectionString);
}
修订由约翰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();
}
}
}
这篇关于使用MVC-迷你探查与EF 4.0和Ninject的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文