Configure Multiple Database Entity Framework 6

Using Entity Framework with Multiple Databases and Providers in the Same Project (SQL Server and MySql)

With the help of Microsoft, I finally figured it out. Hopefully this helps someone else out there. I had to create my own class inheriting from DbConfiguration

public class MyCustomSQLDbConfiguration : DbConfiguration
{
public MyCustomSQLDbConfiguration()
{
SetExecutionStrategy("MySql.Data.MySqlClient", () => new MySqlExecutionStrategy());
SetDefaultConnectionFactory(new LocalDbConnectionFactory("mssqllocaldb"));
}
}

Then decorate my MySqlDBContext accordingly:

[DbConfigurationType(typeof(MyCustomSQLDbConfiguration))]
public class MySqlDBContext : DbContext
{
public MySqlDBContext() : base("MySqlDBContext")
{

}
}

And then finally (and importantly), explicitly set this when I run the application. In the case of a console app, at the beginning of Program.Main, or in a web application, on Application_Start:

DbConfiguration.SetConfiguration(new MyCustomSQLDbConfiguration());

Entity Framework 6: Creating database with multiple contexts

I ended up using DbMigrator. You need to setup migration configuration classes for your contexts and do the following per context.

        var migrationConfig = new MyApp.Data.Migrations.Configuration
{
TargetDatabase = new DbConnectionInfo(tenantProfile.ConnectionString, "MySql.Data.MySqlClient")
};
var migrator = new DbMigrator(migrationConfig);
migrator.Update();

Using entity framework on multiple databases

EF6 has better support for multiple DB access from Same context. Here is a snippet from EF5.
Managing the database initializer setting prior is important.
You may not want to trigger ANY migrations.
i.e, use this before

Database.SetInitializer(new ContextInitializerNone<MyDbContext>());

but to answer the question: Yes you can

var conn = GetSqlConn4DbName(dataSource,dbName );
var ctx = new MyDbContext(conn,true);

public DbConnection GetSqlConn4DbName(string dataSource, string dbName) {
var sqlConnStringBuilder = new SqlConnectionStringBuilder();
sqlConnStringBuilder.DataSource = String.IsNullOrEmpty(dataSource) ? DefaultDataSource : dataSource;
sqlConnStringBuilder.IntegratedSecurity = true;
sqlConnStringBuilder.MultipleActiveResultSets = true;

var sqlConnFact = new SqlConnectionFactory(sqlConnStringBuilder.ConnectionString);
var sqlConn = sqlConnFact.CreateConnection(dbName);
return sqlConn;
}

public class ContextInitializerNone<TContext> : IDatabaseInitializer<TContext> where TContext : DbContext
{
public void InitializeDatabase(TContext context) { }
}

Also see StackOverflow answer using migration, sample code, and dynamic db connection



Related Topics



Leave a reply



Submit