How to Build a Multi-Tenant SaaS Application in ASP.NET Core 10 Using EF Core (2026)
A customer can guess or obtain an order ID through a support ticket, email, or log. A multi-tenant SaaS API must make that ID useless outside the owning tenant. In ASP.NET Core 10, start with a validated access token, resolve the tenant from a trusted claim, and bind EF Core queries and writes to that tenant. The sample below shows this with a shared SQLite database.
Choose the isolation model
| Model | Useful when | What you own |
|---|---|---|
| Shared database and tables | Many tenants share one release and schema | Filtering, composite keys, per-tenant restore strategy |
| Database per tenant | A customer needs separate retention, keys, or restores | Provisioning, credentials, migration fleet, connection limits |
| Dedicated infrastructure | Isolation or residency extends beyond storage | Deployment fleet and operational cost |
The sample uses shared tables. An order ID identifies a row only together with a tenant ID. A global query filter adds the tenant predicate to ordinary EF queries. EF Core 10 named filters make it possible to disable a soft-delete filter independently if you introduce one later. Restrict filter bypasses to separately authorized administrative code.
Set up the API and token issuer
Install the .NET 10 SDK. Create the project and use the current supported patch in the EF Core and ASP.NET Core 10 package lines.
Configure an HTTPS OpenID Connect issuer and API audience using Auth__Authority and Auth__Audience. The issuer must issue access tokens for this audience with one tenant_id claim containing a nonempty GUID. Configure the issuer to derive that claim from verified membership. Most identity providers need custom claim configuration, and a directory tenant identifier is only suitable when it matches the application tenant boundary.
Implement tenant resolution and database access
Replace Program.cs. For local use, the Development environment initializes a fresh SQLite file. Start from an empty file. Production deployments should apply reviewed migrations under a separate database identity. This sample accepts authenticated tenant members for both endpoints, so use explicit roles or permissions if only some members should create orders.
The API takes the order summary from the request. It takes the tenant ID from the principal and generates the order ID. The query binds the filter to the current context instance, allowing the EF model to be reused safely across requests. Keep the tenant resolver and context request-scoped. Avoid putting tenant IDs in global state or creating a DbContext singleton.
Test tenant boundaries with real tokens
Run ASPNETCORE_ENVIRONMENT=Development dotnet run --no-launch-profile --urls http://localhost:5071. Use real development tokens from the configured issuer. Create an order with tenant A, then take the ID from the Location header. Repeat the read with tenant B. HTTP here is loopback only. Use HTTPS for deployed clients.
Expected results are 201 on creation, 200 for the owner, 404 for tenant B, 401 for invalid or missing authentication, and 403 for an authenticated token without a valid tenant claim. Re-run the negative case after adding new endpoints, including list and export. Test two seeded records with the same order ID in distinct tenants and verify that each request returns exactly the matching row.
Migrations, onboarding and security
Create a production tenant registry and update memberships when users join or leave. Set short-lived access tokens if revocation needs to take effect promptly, or verify active membership at the application boundary. Provision tenant defaults idempotently and place tenant IDs on background jobs explicitly so workers can create a scoped context without an HTTP request.
Model child relationships with tenant-aware foreign keys. Scope cache keys and object storage paths with tenant IDs too. Review raw SQL, bulk APIs and IgnoreQueryFilters() separately. An EF filter controls query composition. Database row-level policies, credentials, and audit trails can add protection when application code has multiple paths to the database.
How do I handle migrations across databases?
Apply migrations using a dedicated deployment step. For database-per-tenant, track version and status per tenant, run in bounded batches, and separate a failed tenant from the fleet. Test recovery from a partially upgraded fleet before onboarding customers.
Why did an authorized request get 404?
Verify that the token belongs to the expected tenant and that the stored row has the same tenant ID. Inspect parameterized query logging in a safe development environment. Keep sensitive data logging off in production.
Add isolation to every access path
A filter on Orders does not automatically authorize a file download or an export. Identify the data boundary for each feature and include it in review. An order-line table can use a foreign key containing both the tenant and order ID. A search index can carry tenant scope on every record and require that scope in the server query. A message handler can read the tenant from trusted message metadata, then use a separate worker-scoped resolver with no dependence on the HTTP request.
Watch for bulk update endpoints and concurrency conflicts. Derive ownership before writing and include tenant identity in the mutation predicate. An optimistic concurrency token helps detect updates by two members of the same tenant, while tenant isolation determines whether either caller can address the record. Test those concerns independently. Use a real relational test database for the filter and key tests so the provider translates the predicate to SQL.
For incident triage, record trace IDs and access decisions with appropriate tenant audit data, protected according to policy. Review exports, administrator impersonation, and support tooling explicitly. They often bypass normal request paths and need their own authorization policies and audit records.
Comments
Post a Comment