heymega
heymega

Reputation: 9411

EF Multiple databases with one context

I have a context in my database that points to 3 child database instances. I inject the correct db connection string via the context's construtor.

However I'm having difficulty getting this to work with automatic migrations. The issue is, automatic migrations expects a a parameterless constructor which I can't provide and IDbContextFactory only allows me to return one connection string.

Is there a way I can get the migration scripts to run against multiple databases or would I need to create 3 separate contexts?

Upvotes: 9

Views: 4230

Answers (1)

Anthony Brenelière
Anthony Brenelière

Reputation: 63620

Each instance of your context has one database connection.

Assuming that each child database wille have the same code-first model, you can launch one instance of the same context class for each database.

Just call DbContext.Initialize( true ) to migrate the database, then close the connection.

var context1 = new MigratorContext( connectionString1 );
context1.Initilialize( true );
var context2 = new MigratorContext( connectionString2 );
context2.Initilialize( true );
var context3 = new MigratorContext( connectionString3 );
context3.Initilialize( true );

Add a constructor for MigratorContext taking the connection string:

public MigratorContext(string connString)
   : base( connString)
{
    var migrationConfiguration = new MigrationConf();

    Database.SetInitializer<MigratorContext>(
        new MigrateDatabaseToLatestVersion<
            MigratorContext, MigrationConf>(true, migrationConfiguration));
}

public sealed class MigrationConf : DbMigrationsConfiguration<MigratorContext>
{
    public MigrationConf()
        : base()
    {
        AutomaticMigrationsEnabled = true;
        AutomaticMigrationDataLossAllowed = true;
    }
}

Upvotes: 6

Related Questions