我正在尝试将EF Tracing实用程序与EF 5.0(代码优先)一起使用。但这只适用于需要edmx文件的对象上下文。
http://code.msdn.microsoft.com/EFProviderWrappers
是否有人首先使用DBContext解决EF代码的问题?
阿南德
答案 0 :(得分:1)
在网站的问答部分,作者使用此代码使用Code First:
在DbContext中使用DbCommand构造函数重载...
var context = new NorthwindContext(CreateConnectionWrapper(@"name=NorthwindContext"));
CreateConnectionWrapper方法:
private static DbConnection CreateConnectionWrapper(string nameOrConnectionString) {
var providerInvariantName = "System.Data.SqlClient";
var connectionString = nameOrConnectionString;
//name=connectionName format
var index = nameOrConnectionString.IndexOf('=');
if (nameOrConnectionString.Substring(0, index).Trim()
.Equals("name", StringComparison.OrdinalIgnoreCase))
{
nameOrConnectionString = nameOrConnectionString
.Substring(index + 1).Trim();
}
//look up connection string name
var connectionStringSetting =
ConfigurationManager.ConnectionStrings[nameOrConnectionString];
if (connectionStringSetting != null)
{
providerInvariantName = connectionStringSetting.ProviderName;
connectionString = connectionStringSetting.ConnectionString;
}
//create the special connection string with the provider name in it
var wrappedConnectionString = "wrappedProvider=" +
providerInvariantName + ";" +
connectionString;
//create the tracing wrapper
var connection = new EFTracingConnection
{
ConnectionString = wrappedConnectionString
};
//hook up logging here
connection.CommandFinished +=
(sender, args) => Console.WriteLine(args.ToTraceString());
return connection; }
这只是TracingWrapper,但你也可以用同样的方式包装Caching包装器。