没有配置文件的实体框架跟踪提供程序包装器

Luk*_*rkl 4 c# entity-framework-4

我想在SQLCE4数据库中使用Entity Framework Code第一种方法.一切似乎都很好,但我有调试SQL查询的问题.我发现来自http://efwrappers.codeplex.com/的 EFTracing 应该是我需要的,但我不知道如何在没有app.config文件的情况下使用它.我不是这种配置的忠实粉丝.我想只使用C#代码来设置和运行所有内容.我认为使用这样的代码应该没问题:

using (System.Data.Common.DbConnection c = 
    new EFTracingProvider.EFTracingConnection(
        new System.Data.SqlServerCe.SqlCeConnection(conn)))
{
    using (var context = new MyContext(c))
    {
        var a = from data in context.Projects select data;
    }
}
Run Code Online (Sandbox Code Playgroud)

但它不起作用.它抛出异常:

无法确定连接类型EFTracingProvider.EFTracingConnection的提供程序名称.

有没有简单的方法如何只在代码中正确创建包装连接?

Luk*_*rkl 6

我的问题的解决方案是遵循DbContext对象.

public class MyContext : DbContext
{
  public MyContext()
    : base(CreateConnection("Data Source=file.sdf", 
                            "System.Data.SqlServerCe.4.0"), true)
  { }

  public DbSet<Project> Projects { get; set; }

  public static bool TraceEnabled = true;

  private static DbConnection CreateConnection(string connectionString, 
                                               string providerInvariantName)
  {
    DbConnection connection = null;
    if (TraceEnabled)
    {
      EFTracingProviderConfiguration.RegisterProvider();
      EFTracingProviderConfiguration.LogToConsole = true;
      string wrapperConnectionString = String.Format(@"wrappedProvider={0};{1}",
         providerInvariantName, connectionString);
      connection = new EFTracingConnection() 
      { 
        ConnectionString = wrapperConnectionString 
      };
    }
    else
    {
      DbProviderFactory factory = DbProviderFactories.GetFactory(providerInvariantName);
      connection = factory.CreateConnection();
      connection.ConnectionString = connectionString;
    }
    return connection;
  }
}
Run Code Online (Sandbox Code Playgroud)

所以现在我可以使用上下文,并根据TraceEnabled属性自动为包装或解包的SqlCe创建连接.

using (var context = new MyContext())
{
    var a = context.Projects.FirstOrDefault();
}
Run Code Online (Sandbox Code Playgroud)