Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 913
Shyam Avatar asked Mar 12 '19 14:03

Shyam


People also ask

Can we use multiple database in Entity Framework?

Multiple DbContext was first introduced in Entity Framework 6.0. Multiple context classes may belong to a single database or two different databases.

How does EF core migration work?

EF Core compares the current model against a snapshot of the old model to determine the differences, and generates migration source files; the files can be tracked in your project's source control like any other source file. Once a new migration has been generated, it can be applied to a database in various ways.

Is EF core fast?

EF Core 6.0 performance is now 70% faster on the industry-standard TechEmpower Fortunes benchmark, compared to 5.0. This is the full-stack perf improvement, including improvements in the benchmark code, the . NET runtime, etc. EF Core 6.0 itself is 31% faster executing queries.


Video Answer


1 Answers

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.

like image 90
KenR Avatar answered Sep 23 '22 08:09

KenR