This is a POC showing how one can use Entity Framework with a Postgres DB per tenant. Different tenant identification strategies can be used. The following ones are implemented:
-
Using a request header (
X-Tenant
) to provide the tenant and a database lookup to map the tenant
DbTenantIdentificationService.cs
-
Using a request header (
X-Tenant
) to provide the tenant and a configuration file lookup to map the tenant
HeaderTenantIdentificationService.cs
-
Using the request
host
to provide the tenant and a configuration file lookup to map the tenant
HostTenantIdentificationService.cs
To use multiple DbScope objects one must use generic options in the constructor (DbContextOptions<T>
).
It is also advised to implement factory objects to generate the DB context objects when using tools such as dotnet ef migrations
(see: https://docs.microsoft.com/en-us/ef/core/miscellaneous/cli/dbcontext-creation)
-
To create the (first) migration for the tenants context use:
dotnet ef migrations add InitialCreate --context TenantsDbContext -o Migrations/Tenants
-
To create the SQL scripts for the (first) migration for the tenants context use:
dotnet ef migrations script --context TenantsDbContext -o Migrations/Tenants/scripts/00-initial-create.sql
-
To create the (first) migration for the blogs context use:
dotnet ef migrations add InitialCreate --context BlogsDbContext -o Migrations/Blogs
-
To create the SQL scripts for the (first) migration for the tenants context use:
dotnet ef migrations script --context BlogsDbContext -o Migrations/blogs/scripts/00-initial-create.sql