First of all, you are using the wrong configuration classes. The type DbConfigurationType needs a type inherited from DbConfiguration, not DbMigrationsConfiguration <>.
DbMigrationsConfiguration is really only used for Migrators and DatabaseInitializers.
public class MyDbConfiguration : DbConfiguration { public MyDbConfiguration() { this.SetDefaultConnectionFactory(new System.Data.Entity.Infrastructure.SqlCeConnectionFactory("System.Data.SqlServerCe.4.0")); this.SetProviderServices("System.Data.SqlServerCe.4.0", SqlCeProviderServices.Instance); this.AddInterceptor(new NLogCommandInterceptor());
Unfortunately, it is not possible to set multiple DefaultConnectionFactories even with multiple DbConfigurations.
In your case, you will need to save the connection strings in app.config and pass the name to the DbContext constructor.
public class TestContext : DbContext { public TestContext() : base("name=MyConnectionString") { }
The connection will be initialized based on the provider name for MyConnectionString in app.config
Or if you do not want the connection string in your app.config to simply pass the already initialized DbConnection to the DbContext constructor
public class TestContext : DbContext { public TestContext() : base(new SqlCeConnection(GetConnectionString()),true) { }
Or if you do not want to initialize a specific connection, use DbProviderFactory.
public class TestContext : DbContext { public TestContext() : base(GetConnection(),true) { } public static DbConnection GetConnection() { var factory = DbProviderFactories.GetFactory("System.Data.SqlServerCe.4.0"); var connection = factory.CreateConnection(); connection.ConnectionString = "Data Source=C:/teste2.sdf;Persist Security Info=False;"; return connection; }
source share