How to configure EF Tracing provider for EF code first

前提是你 提交于 2020-01-16 19:08:16

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!