The bug that ends a SaaS business isn't a crash. It's one customer opening a page and seeing another customer's invoices.

The usual defence is a Where(x => x.OrganizationId == orgId) on every query. That works until someone writes the one query that forgets it. A code review might catch it. A test might not, because the test only has one organization in it.

When I built the multi-tenant core of ShipBlazor, I wanted forgetting to be impossible. The rule moved out of the queries and into the DbContext, which now does three things for every table that belongs to an organization:

Filters every read to the current organization.
Stamps every new row with the current organization.
Throws on any write to another organization's row.

Here's how each part works, with the tests that check it. All the code is in a free, MIT-licensed repository linked at the end.

Step 1: mark the data that belongs to an organization

One interface marks tenant-owned data:

csharp
public interface ITenantEntity
{
Guid OrganizationId { get; set; }
}

public class Project : ITenantEntity
{
public Guid Id { get; set; } = Guid.CreateVersion7();
public Guid OrganizationId { get; set; }
public required string Name { get; set; }
}

That's the only thing a developer adds to a new entity. Everything below happens automatically.

Step 2: filter every read

The context carries the current organization in a property:

csharp
public abstract class ApplicationDbContext(DbContextOptions options)
: IdentityDbContext(options)
{
public Guid? TenantId { get; set; }
}

In OnModelCreating, every entity that implements ITenantEntity gets a global query filter that compares its OrganizationId with that property:

csharp
var tenantTypes = builder.Model.GetEntityTypes()
.Select(t => t.ClrType)
.Where(t => typeof(ITenantEntity).IsAssignableFrom(t))
.ToList();

foreach (var type in tenantTypes)
{
ApplyTenantFilterMethod.MakeGenericMethod(type).Invoke(this, [builder]);
}

private void ApplyTenantFilter(ModelBuilder builder) where T : class, ITenantEntity
=> builder.Entity().HasQueryFilter(e => e.OrganizationId == TenantId);

The filter refers to TenantId on the context, so EF Core reads the value from whichever context instance runs the query. One model, many tenants. The EF Core docs on global query filters describe this pattern for multi-tenancy.

Two details matter:

It fails closed. If TenantId is null, OrganizationId == null matches nothing. A page that forgot to set the organization shows an empty list, not everyone's data.
Lookups by id find nothing. db.Projects.FirstOrDefaultAsync(p => p.Id == id) with another organization's id returns null, so the page shows "not found". You never write "found it, but you're not allowed", which would confirm the id exists.
Step 3: stamp new rows and refuse foreign writes

Reads are half the job. SaveChanges checks every tenant entity it's about to write:

csharp
public override Task SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = default)
{
EnforceTenant();
return base.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken);
}

private void EnforceTenant()
{
foreach (var entry in ChangeTracker.Entries())
{
if (entry.State == EntityState.Added && entry.Entity.OrganizationId == Guid.Empty)
{
entry.Entity.OrganizationId = TenantId
?? throw new InvalidOperationException("Cannot add tenant data without a current organization.");
}

 var isWrite = entry.State is EntityState.Added or EntityState.Modified or EntityState.Deleted; if (isWrite && entry.Entity.OrganizationId != TenantId) { throw new InvalidOperationException( $"Blocked a write to {entry.Entity.GetType().Name} belonging to another organization."); } } 

}

New rows get the organization without anyone setting it. A row that arrives with someone else's OrganizationId (a tampered form, a bug in a mapper) stops the whole save with an exception, so nothing is written.

(The real method also has an escape hatch for trusted system code such as imports, which must write rows for many organizations. It's a separate flag, AllowCrossTenantWrites, that request-handling code never sets.)

Step 4: where TenantId comes from

The organization never comes from the request. It comes from the signed-in user's membership, read from the database. Blazor pages get their context from one small service:

csharp
public async Task CreateDbContextAsync()
{
var tenant = await GetCurrentAsync()
?? throw new InvalidOperationException("No current organization. Send the user to /onboarding first.");

var db = await dbFactory.CreateDbContextAsync(); db.TenantId = tenant.OrganizationId; return db; 

}

GetCurrentAsync looks up the user's current organization and checks they're still a member. Switching organizations changes that record, after the same membership check. A page then reads like ordinary EF Core code, with no tenant logic in sight:

csharp
await using var db = await Tenant.CreateDbContextAsync();
projects = await db.Projects.OrderByDescending(p => p.CreatedUtc).ToListAsync();

It uses IDbContextFactory rather than an injected context because Blazor components can live longer than one request. Each operation gets a fresh, short-lived context.

What this does not protect

It's a safety net, not magic. Know where the holes are:

ExecuteUpdate and ExecuteDelete are narrowed by the filter (I test this below), but they skip SaveChanges, so the write check doesn't run.
Raw SQL (FromSql, ExecuteSql) ignores filters completely. Filter by OrganizationId yourself.
IgnoreQueryFilters() turns the filter off. Keep it to background jobs and admin tools, never code that handles a customer's request.
Required navigations to a filtered entity become inner joins and can drop rows. The EF Core docs explain the fix.

A tip for EF Core 10: filters can now have names. If you later add soft delete, name both (HasQueryFilter("Tenant", ...) and HasQueryFilter("SoftDelete", ...)). Then an admin screen can show deleted rows with IgnoreQueryFilters(["SoftDelete"]) while tenant isolation stays on.

The tests that keep it honest

Isolation that isn't tested will break during some refactor next year. These tests start the real app in memory with WebApplicationFactory, create two organizations, and try to cross the line:

csharp
[Fact]
public async Task Writing_another_organizations_row_is_refused()
{
var acme = await factory.CreateTenantAsync();
var globex = await factory.CreateTenantAsync();
await using var db = await factory.TenantDbAsync(acme.OrganizationId);
db.Projects.Add(new Project { Name = "Sneaky", OrganizationId = globex.OrganizationId });

var error = await Assert.ThrowsAsync<InvalidOperationException>(() => db.SaveChangesAsync()); Assert.Contains("another organization", error.Message); 

}

The suite checks five things: reads only see the current organization, new rows are stamped, foreign writes are refused, bulk updates and deletes stay inside the organization, and no organization means no rows. GitHub Actions runs it on SQLite and PostgreSQL for every push, because a filter that works on one database provider can surprise you on another.

Try it

All of this is in ShipBlazor Lite, a free, MIT-licensed .NET 10 Blazor starter: sign-in with two-factor and passkeys, organizations, roles, email invitations, an activity log, and the isolation and tests above.

Repository: https://github.com/shipblazor/shipblazor-lite
ApplicationDbContext.cs and TenantIsolationTests.cs are the two files to read first.

If you also need Stripe billing, a public API, webhooks and metered AI, there's a paid edition, ShipBlazor Pro, built on the same core.

How do you handle tenant isolation in your apps: a filter like this, a database per tenant, or row-level security in the database? I'd like to hear what's worked for you.