2

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.

1
  • The difference is in this case the database initialization needs to be done though application code not nuget package manager. Commented Jul 2, 2015 at 0:28

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.