问题
i am trying to use EF Tracing utility with EF 5.0 (code first). but this works only object context which requires edmx file.
http://code.msdn.microsoft.com/EFProviderWrappers
anybody is having workaround for EF code first with DBContext?
anand
回答1:
From the Q&A section of the site, the author has this code for using Code First:
Use the DbCommand constructor overload in your DbContext...
var context = new NorthwindContext(CreateConnectionWrapper(@"name=NorthwindContext"));
And the CreateConnectionWrapper method:
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; }
This just does the TracingWrapper, but you can also wrap the Caching wrapper in the same way.
来源:https://stackoverflow.com/questions/12535079/how-to-configure-ef-tracing-provider-for-ef-code-first