EF6 / SQL Server Compact,基于代码的配置

时间:2015-04-16 17:35:47

标签: c# entity-framework .net-4.0 sql-server-ce

我尝试将我的EF6配置从myexe.exe.config移到代码作为empty DbProviderFactories node in machine.config - 问题的解决方法(此处描述:https://stackoverflow.com/a/24273922/600559)。我不想更改machine.config文件。

我已阅读Code-Based Configuration (EF6 onwards)

我尝试过这样的实现:https://stackoverflow.com/a/23130602/600559但是我无法让它工作。有没有人有一个有效的EF6 / SQL CE /基于代码的配置解决方案?

这是我的更改(从工作的.config解决方案到基于代码的解决方案): 新课程增加:

public class DatabaseConfiguration : DbConfiguration
{
    public DatabaseConfiguration()
    {
        SetExecutionStrategy("System.Data.SqlServerCe.4.0", () => new DefaultExecutionStrategy());
        SetProviderFactory("System.Data.SqlServerCe.4.0", new SqlCeProviderFactory());
        SetProviderServices("System.Data.SqlServerCe.4.0", SqlCeProviderServices.Instance);
    }
}

然后删除system.data文件中的entityFramework.config节点。

现在这样可行,但会读取machine.config个文件:如果<DbProviderFactories/>中有machine.config,我会收到此异常:

Exception

所以真正的问题不是基于代码的配置不起作用,问题是machine.config配置仍然被读取并导致问题。谁知道如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

找到解决方案。实现不从IDbProviderFactoryResolver文件中读取的machine.config

  public class CodeBasedDatabaseConfiguration : DbConfiguration
  {
    public CodeBasedDatabaseConfiguration()
    {
      SetExecutionStrategy("System.Data.SqlServerCe.4.0", () => new DefaultExecutionStrategy());
      SetProviderFactory("System.Data.SqlServerCe.4.0", new SqlCeProviderFactory());
      SetProviderServices("System.Data.SqlServerCe.4.0", SqlCeProviderServices.Instance);
      SetProviderFactoryResolver(new CodeBasedDbProviderFactoryResolver());
    }
  }

  internal class CodeBasedDbProviderFactoryResolver : IDbProviderFactoryResolver
  {
    private readonly DbProviderFactory sqlServerCeDbProviderFactory = new SqlCeProviderFactory();

    public DbProviderFactory ResolveProviderFactory(DbConnection connection)
    {
      var connectionType = connection.GetType();
      var assembly = connectionType.Assembly;
      if (assembly.FullName.Contains("System.Data.SqlServerCe"))
      {
        return sqlServerCeDbProviderFactory;
      }
      if (assembly.FullName.Contains("EntityFramework"))
      {
        return EntityProviderFactory.Instance;
      }
      return null;
    }
  }