Blog
04 · Clean Architecture: CQRS & CloudPart 0216 min read

Industrial-Scale B2B SaaS Architecture: Multi-Tenancy Isolation, EF Core Global Filters, and RBAC

How do you architecturally guarantee zero cross-tenant data leakage when 500 enterprise companies share a B2B SaaS platform? Master Multi-Tenancy strategies, EF Core Global Query Filters, automated SaveChanges TenantId stamping, and Permission-Based RBAC in .NET 9.

Emirhan Uluksar
Emirhan Uluksar

Founder & Principal Software Architect · Digital HAT

0 views
Industrial-Scale B2B SaaS Architecture: Multi-Tenancy Isolation, EF Core Global Filters, and RBAC

When engineering a multi-tenant B2B SaaS platform—such as our SafeWork360 enterprise OHS platform or DHRevora multi-branch POS suite—the single most critical architectural requirement is **strict tenant isolation**. If data isolation relies on individual developers remembering to type .Where(x => x.TenantId == currentTenantId) in every query, human error will eventually cause a cross-tenant data leak.

In this comprehensive guide, we build an automated, zero-trust Multi-Tenancy & RBAC Architecture in .NET 9 where tenant filtering and tenant stamping happen automatically inside the persistence pipeline.

What You Will Master in This Guide:
1. Comparing Multi-Tenancy Models: Database-per-Tenant vs. Schema-per-Tenant vs. Pooled Shared-Table (TenantId + Row-Level Security).
2. Complete folder and file directory tree for a multi-tenant .NET 9 solution.
3. Resolving the authenticated tenant via ITenantContext and JWT claims.
4. Enforcing automatic WHERE TenantId = @p0 filters using EF Core Global Query Filters.
5. Preventing tenant-spoofing on write operations by stamping TenantId inside SaveChangesAsync.
Industrial B2B SaaS Architecture: Multi-Tenancy Isolation, EF Core Global Filters and RBAC

1. Multi-Tenant B2B SaaS Solution Directory Tree

src/
├── DigitalHat.SaaS.Domain/
│   └── Common/ITenantEntity.cs                  # Contract for all tenant-scoped aggregates
├── DigitalHat.SaaS.Application/
│   └── Abstractions/MultiTenancy/ITenantContext.cs
├── DigitalHat.SaaS.Infrastructure/
│   ├── MultiTenancy/HttpTenantContext.cs        # Extracts verified tenant_id from JWT claims
│   └── Persistence/SaaSDbContext.cs             # Global Query Filters & SaveChanges stamping
└── DigitalHat.SaaS.WebApi/
    └── Middlewares/TenantResolutionMiddleware.cs

2. Automated Read & Write Tenant Isolation (SaaSDbContext.cs)

// File: src/DigitalHat.SaaS.Infrastructure/Persistence/SaaSDbContext.cs
using System;
using System.Threading;
using System.Threading.Tasks;
using DigitalHat.SaaS.Application.Abstractions.MultiTenancy;
using DigitalHat.SaaS.Domain.Common;
using Microsoft.EntityFrameworkCore;

public class SaaSDbContext : DbContext
{
    private readonly ITenantContext _tenantContext;

    public SaaSDbContext(DbContextOptions<SaaSDbContext> options, ITenantContext tenantContext)
        : base(options)
    {
        _tenantContext = tenantContext;
    }

    public DbSet<SafetyIncident> SafetyIncidents => Set<SafetyIncident>();

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        // 1. AUTOMATIC READ ISOLATION:
        // Every SELECT query automatically appends 'WHERE TenantId = @currentTenantId'
        modelBuilder.Entity<SafetyIncident>()
            .HasQueryFilter(e => e.TenantId == _tenantContext.CurrentTenantId);

        modelBuilder.Entity<SafetyIncident>()
            .HasIndex(e => new { e.TenantId, e.Id });
    }

    public override Task<int> SaveChangesAsync(CancellationToken cancellationToken = default)
    {
        // 2. AUTOMATIC WRITE ISOLATION:
        // Never trust a client-supplied TenantId in JSON payloads; stamp the verified JWT tenant!
        foreach (var entry in ChangeTracker.Entries<ITenantEntity>())
        {
            if (entry.State == EntityState.Added)
            {
                if (_tenantContext.CurrentTenantId == Guid.Empty)
                    throw new UnauthorizedAccessException("Cannot persist tenant entity without an active TenantContext.");

                entry.Entity.TenantId = _tenantContext.CurrentTenantId;
            }
        }

        return base.SaveChangesAsync(cancellationToken);
    }
}

Did you find this engineering guide helpful?

Give it a like or share it with your team and network.

0 views
Share This Guide: