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
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