Siamak S.
Siamak S.

Reputation: 81

Entity Framework 6: Creating database with multiple contexts

I'm working on a multi-tenant application for which we decided to have a database per tenant. I'm coding a service to create and initialize a new database for a new client. Multiple contexts are defined on the same DB. So far I've used nuget update-database to have all the contexts create their db objects. Now I need to do the same at runtime. I tried:

context.Database.Initialize(false); context.Database.CreateIfNotExists();

But only the first context creates its table. I know that a context initializes the db on the first use but apparently it doesn't if the db already exists. I tried several initializers with no luck. I don't want to code a new context which combines all other contexts because it would be difficult to maintain. I know another option would be generating sql scripts at deployment and executing them at runtime. This would be my last resort.

Any suggestion is highly appreciated.

Upvotes: 2

Views: 3416

Answers (2)

bubi
bubi

Reputation: 6501

EF6 does support initialization for multiple contexts. It's based on ContextKey (property and new field on __MigrationHistory).
It support your (same as mine) multi tennant approach based on multiple databases.
I know is bad to add a link but this article is very well done: https://msdn.microsoft.com/en-us/magazine/dn948104.aspx

Upvotes: 1

Siamak S.
Siamak S.

Reputation: 81

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();

Upvotes: 0

Related Questions