In a shared-database SaaS every table holds rows for every customer, and a single missing WHERE CompanyId = @CompanyId is a data leak. On the fleet management platform I built this year, I didn't want tenant isolation to depend on every developer remembering that clause in every query. EF Core's global query filters make it the default instead. Here is the setup I use and the gaps you still have to close by hand.
1. A tenant context per request
First, something scoped to the request that knows which company the current user belongs to. Reading it from a claim issued at login means it costs nothing per query.
public interface ITenantContext
{
int? CompanyId { get; }
}
public sealed class ClaimsTenantContext(IHttpContextAccessor accessor) : ITenantContext
{
public int? CompanyId =>
int.TryParse(accessor.HttpContext?.User.FindFirst("company_id")?.Value, out var id) ? id : null;
}
2. Mark tenant-owned entities
public interface ITenantOwned
{
int CompanyId { get; set; }
}
3. Apply the filter to every tenant-owned entity
The important detail: the filter must reference a property on the DbContext, not a value captured when the model is built. EF Core caches the model once, but it re-evaluates context members for each query, so each request sees its own tenant.
public class AppDbContext(DbContextOptions<AppDbContext> options, ITenantContext tenant) : DbContext(options)
{
public int? CurrentCompanyId => tenant.CompanyId;
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
foreach (var entityType in modelBuilder.Model.GetEntityTypes()
.Where(t => typeof(ITenantOwned).IsAssignableFrom(t.ClrType)))
{
// e => e.CompanyId == this.CurrentCompanyId
var e = Expression.Parameter(entityType.ClrType, "e");
var body = Expression.Equal(
Expression.Convert(Expression.Property(e, nameof(ITenantOwned.CompanyId)), typeof(int?)),
Expression.Property(Expression.Constant(this), nameof(CurrentCompanyId)));
entityType.SetQueryFilter(Expression.Lambda(body, e));
}
}
}
If there is no tenant (an anonymous request), CurrentCompanyId is null and the comparison matches nothing. That is the failure mode you want: an empty list, not everybody's data.
4. Stamp and guard on save
Filters only protect reads. For writes, set the tenant on new rows and refuse changes to rows that belong to someone else:
public override Task<int> SaveChangesAsync(CancellationToken ct = default)
{
foreach (var entry in ChangeTracker.Entries<ITenantOwned>())
{
if (entry.State == EntityState.Added && entry.Entity.CompanyId == 0)
entry.Entity.CompanyId = CurrentCompanyId
?? throw new InvalidOperationException("No tenant for this request.");
if (entry.State is EntityState.Modified or EntityState.Deleted
&& entry.Entity.CompanyId != CurrentCompanyId)
throw new InvalidOperationException("Cross-tenant write blocked.");
}
return base.SaveChangesAsync(ct);
}
Where the filters don't reach
- Raw SQL, Dapper and stored procedures. Filters are applied when EF translates LINQ. Anything you write by hand bypasses them. On the fleet platform the company-scoped stored procedures take
@CompanyIdas a parameter, and it should always come from the tenant context — never from the request body. IgnoreQueryFilters(). Sometimes needed for platform-admin screens. Keep it rare and easy to find with a search; I wrap it in a clearly named repository method rather than sprinkling it through controllers.- Background jobs. A Quartz job has no
HttpContext, so the claims-based tenant is null and every query returns nothing. Jobs that work per tenant should loop over companies and set an explicit tenant scope for each pass. - Other filters. Before EF Core 10, an entity can have only one query filter, so a soft-delete filter must be combined with the tenant check in the same expression. EF Core 10 adds named filters, which makes this tidier.
Test it
The one test I would not skip: create two companies, add data for each, sign in as the first, and assert that every list endpoint returns none of the second company's rows. It catches the stored procedure someone forgot to scope far sooner than a customer will.