WPalombini
WPalombini

Reputation: 961

EF Code First Migrations for multiple databases

I have prototyped a project using EF 6 Code First MVC 5 based on this solution:

EF Code First to create multiple databases dynamically

Now I would like to know how Migrations would work with multiple databases?

Does it mean I am going to need to run the Add-Migration MigrationsName for every database I have?

Upvotes: 3

Views: 3961

Answers (1)

Yuliam Chandra
Yuliam Chandra

Reputation: 14640

You just confirmed that all databases need to be upgraded the same time, then you only need to use one database to add the migration, then update it to all databases.

You can specify the connection string name parameter based on connection string name in the config.

<connectionStrings>
    <add name="CompanyABC"
         connectionString="Data Source=.; Initial Catalog=CompanyABC; Integrated Security = true;" 
         providerName="System.Data.SqlClient" />
    <add name="CompanyDEF"
         connectionString="Data Source=.; Initial Catalog=CompanyDEF; Integrated Security = true;"
         providerName="System.Data.SqlClient" />
    <add name="CompanyXYZ"
         connectionString="Data Source=.; Initial Catalog=CompanyXYZ; Integrated Security = true;"
         providerName="System.Data.SqlClient" />
</connectionStrings>

Migration

PM> Enable-Migrations -ConnectionStringName CompanyABC
PM> Add-Migration UpgradeToVersionX -ConnectionStringName CompanyABC
PM> Update-Database -ConnectionStringName CompanyABC
PM> Update-Database -ConnectionStringName CompanyDEF
PM> Update-Database -ConnectionStringName CompanyXYZ

Run Migration at Runtime

Database.SetInitializer<AppContext>(
   new MigrateDatabaseToLatestVersion<AppContext, Configuration>());

Upvotes: 2

Related Questions