0

我正在尝试将 EF Tracing 实用程序与 EF 5.0 一起使用(代码优先)。但这仅适用于需要 edmx 文件的对象上下文。

http://code.msdn.microsoft.com/EFProviderWrappers

有人首先使用 DBContext 解决 EF 代码吗?

阿南德

4

1 回答 1

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 包装器。

于 2012-09-21T18:05:15.163 回答