Entity Framework 6 and migration when I don't have a default Database

491 views Asked by At

I have a solution where I do not have one default database. I have a master Database that are returning a connection string for the customer that is requesting data, and each customer has their own database. I am using migration (and has AutomaticMigrationsEnabled set to false) and code first.

The command “update-database” is “excecuted” from the code (Database.SetInitializer(new MigrateDatabaseToLatestVersion());).

The first time is it all working fine, but when I afterwards will add a migration, I cannot, because there are pending migrations. I can not run update-database from VS because the connections string is set on runtime.

What is the right way to handle a setup like mine, with migrations and Entity Framework 6?

Thanks very much in advance 

2

There are 2 answers

2
Wiktor Zychla On BEST ANSWER

What you have is so called multitenant application. And yes, EF migrations can support such scenario, too.

You just have to change your migrator from the MigrateDatabaseToLatestVersion to a custom one that migrates the exact database the context is created for.

Then, forget about executing update-database from a powershell console. This always updates the default database! Instead, your custom migrator will automatically update the database you connect to.

Complete source code of the custom migrator can be found in my blog entry:

http://www.wiktorzychla.com/2013/05/entity-framework-5-code-first-multi.html

Be aware that due to a bug in eariler versions of EF, migrations in a multitenant scenario work correctly starting from EF 6.1.3.

Because of this bug, your multitenant application could incorrectly assign connection strings to newly created db contexts.

https://entityframework.codeplex.com/SourceControl/changeset/4187b1c308316a22b38ef533b1409024bc0f7406

1
Charles Mager On

Add-Migration and Update-Database from the console still refer to a database.

To create a DbContext, these commands either use its parameterless constructor (if you have one), or it instantiates an IDbContextFactory<T> if one exists and calls its Create method to get one.

The fact you don't use this specific database at run-time isn't really important, but you do need one somewhere at design time to allow you to add migrations.