简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM