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.

An authenticated tenant claim scopes an EF Core query and composite primary key.
An authenticated tenant claim scopes an EF Core query and composite primary key.

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.

BASH
dotnet new web -n TenantOrders -f net10.0
cd TenantOrders
dotnet add package Microsoft.EntityFrameworkCore.Sqlite --version '10.0.*'
dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer --version '10.0.*'

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.

Program.cs
using System.Security.Claims;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddHttpContextAccessor();
builder.Services.AddScoped<Tenant>();
builder.Services.AddDbContext<OrdersDb>(o =>
    o.UseSqlite(builder.Configuration.GetConnectionString("Orders")
        ?? "Data Source=orders.db"));
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(o =>
    {
        o.MapInboundClaims = false;
        o.Authority = builder.Configuration["Auth:Authority"]
            ?? throw new InvalidOperationException("Set Auth__Authority");
        o.Audience = builder.Configuration["Auth:Audience"]
            ?? throw new InvalidOperationException("Set Auth__Audience");
    });
builder.Services.AddAuthorizationBuilder().AddPolicy("Tenant", policy =>
    policy.RequireAuthenticatedUser().RequireAssertion(context =>
        Tenant.Read(context.User) is not null));

var app = builder.Build();
if (app.Environment.IsDevelopment())
{
    await using var scope = app.Services.CreateAsyncScope();
    await scope.ServiceProvider.GetRequiredService<OrdersDb>()
        .Database.EnsureCreatedAsync();
}
app.UseAuthentication();
app.UseAuthorization();

var orders = app.MapGroup("/orders").RequireAuthorization("Tenant");
orders.MapGet("/{id:guid}", async (Guid id, OrdersDb db, CancellationToken ct) =>
{
    var order = await db.Orders.AsNoTracking().Where(x => x.Id == id)
        .Select(x => new OrderDto(x.Id, x.Summary)).SingleOrDefaultAsync(ct);
    return order is null ? Results.NotFound() : Results.Ok(order);
});
orders.MapPost("/", async (NewOrder input, Tenant tenant, OrdersDb db,
    CancellationToken ct) =>
{
    var summary = input.Summary?.Trim();
    if (string.IsNullOrEmpty(summary) || summary.Length > 200)
        return Results.ValidationProblem(new Dictionary<string, string[]>
        {
            ["summary"] = ["Enter between 1 and 200 characters."]
        });
    var order = new Order { TenantId = tenant.Id, Id = Guid.NewGuid(), Summary = summary };
    db.Orders.Add(order);
    await db.SaveChangesAsync(ct);
    return Results.Created($"/orders/{order.Id}", new OrderDto(order.Id, order.Summary));
});
app.Run();

sealed class Tenant(IHttpContextAccessor accessor)
{
    public Guid Id => Read(accessor.HttpContext?.User)
        ?? throw new InvalidOperationException("No authenticated tenant.");

    public static Guid? Read(ClaimsPrincipal? user)
    {
        if (user?.Identity?.IsAuthenticated != true) return null;
        var values = user.FindAll("tenant_id").Select(x => x.Value).ToArray();
        return values.Length == 1 && Guid.TryParse(values[0], out var id)
            && id != Guid.Empty ? id : null;
    }
}
sealed class OrdersDb(DbContextOptions<OrdersDb> options, Tenant tenant) : DbContext(options)
{
    private Guid CurrentTenant => tenant.Id;
    public DbSet<Order> Orders => Set<Order>();

    protected override void OnModelCreating(ModelBuilder model)
    {
        var orders = model.Entity<Order>();
        orders.HasKey(x => new { x.TenantId, x.Id });
        orders.Property(x => x.Summary).HasMaxLength(200);
        orders.HasQueryFilter("TenantIsolation", x => x.TenantId == CurrentTenant);
    }
}
sealed class Order
{
    public Guid TenantId { get; init; }
    public Guid Id { get; init; }
    public string Summary { get; init; } = "";
}
record NewOrder(string? Summary);
record OrderDto(Guid Id, string Summary);

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.

BASH
curl -i http://localhost:5071/orders/ \
  -H "Authorization: Bearer $TOKEN_A" \
  -H 'Content-Type: application/json' \
  -d '{"summary":"Renew annual subscription"}'
curl -i "http://localhost:5071/orders/$ORDER_ID" \
  -H "Authorization: Bearer $TOKEN_B"

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.

References and related reading

Comments