Is there a way to run EF Core migrations on multiple databases having the same set of tables. This is for multi-tenancy architecture where there's a master database (has metadata of all tenant databases including the tenant database connection string) and one database per tenant having the same set of database objects. We need to be able to run these migrations when a new tenant database is created automatically in SaaS model and also run these migrations whenever there are changes to the database structure (new columns, data type changes, new indexes etc.)
I've posted this exact same question on EF Core's GitHub.
The answer is, it can't be done at design time. You basically need to run your migration scripts manually on each tenant's database.
Executing migrations at runtime, however, is easy. You can instantiate a dbContext for each of your connection strings when your app launches (before WebHost.Run() if it's a web app) and execute your migrations like this: dbContext.Database.Migrate();
This is not ideal, of course, because it makes it harder for you to rollback your migrations to a certain point using Visual Studio Package Manager Console or CLI using dotnet ef commands.
The CLI command can be provided a connection string. So you could run it once per db, providing the connection string for each.
The command would look like this:
dotnet ef database update --connection "Server=client1.db;Database=client1"
Our team has about 10 developers, our application is one front-end connect to 20 databases(same scheme), and new database will be add when there is new client. Time to time someone will need update DB scheme, we end up doing this.
- if you need scheme change, create SQL script and create the change request by email
- only one person in the team run those script, and update database access layer
- git push
- tell the team dinner is ready
The person doing this created a EXE project for DB migration, he keep adding script to a folder, so the folder will contain all the script
0001.InitTables.sql
0002.MoreTabels.sql
0003.UpdateDropdowns.sql
.
.
.
then he use a library like DbUp (https://dbup.readthedocs.io/en/latest/) help him track those scripts and run on DB server.
He will run for DEV server first, on the release date, he will run this for production.
List<string> connectionStrings=new List<string>{
"ConStr1","ConStr2", "ConStr3"
};
foreach(var conStr in connectionStrings){
var upgrader = DeployChanges.To
.SqlDatabase(conStr)
.WithScriptsEmbeddedInAssembly(
Assembly.GetExecutingAssembly()
)
.LogToConsole()
.Build();
var result = upgrader.PerformUpgrade();
}
© 2022 - 2024 — McMap. All rights reserved.