Anand Kumar
Anand Kumar

Reputation: 425

How to configure EF Tracing provider for EF code first

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

Upvotes: 0

Views: 531

Answers (1)

Erik Funkenbusch
Erik Funkenbusch

Reputation: 93444

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.

Upvotes: 1

Related Questions