简体   繁体   中英

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM