multi-tenantentity-framework-core-migrations

EF Core Migration - multiple databases


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


Solution

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