Listen to this Post
EF Core has some great features you should know about when building a multi-tenant system:
- Dynamic connection strings
- Query filters for global tenant queries
You’ll need a service to provide the TenantId for the current tenant. This value can be grabbed from a request header or JWT claim. However, a side effect is that you’ll only be able to use the DbContext as part of an HTTP request.
If you’re curious to learn more about what EF Core can offer for building multi-tenant applications, check out this article: https://lnkd.in/eBkbktci
You Should Know:
1. Dynamic Connection Strings in EF Core
To implement dynamic connection strings, you can override the `OnConfiguring` method in your `DbContext` class:
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { var tenantConnectionString = GetTenantConnectionString(); optionsBuilder.UseSqlServer(tenantConnectionString); }
2. Query Filters for Global Tenant Queries
EF Core allows you to apply global query filters to ensure tenant isolation. Here’s how you can implement it:
public class ApplicationDbContext : DbContext { private readonly string _tenantId; public ApplicationDbContext(string tenantId) { _tenantId = tenantId; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<YourEntity>().HasQueryFilter(e => e.TenantId == _tenantId); } }
3. Extracting TenantId from JWT Claims
If you’re using JWT tokens, you can extract the `TenantId` from the claims:
var tenantId = User.Claims.FirstOrDefault(c => c.Type == "TenantId")?.Value;
4. Using DbContext in HTTP Requests
To ensure the `DbContext` is scoped to the HTTP request, register it in the `Startup.cs` file:
services.AddDbContext<ApplicationDbContext>((serviceProvider, options) => { var httpContext = serviceProvider.GetService<IHttpContextAccessor>().HttpContext; var tenantId = httpContext.Request.Headers["TenantId"].ToString(); var connectionString = GetConnectionStringForTenant(tenantId); options.UseSqlServer(connectionString); });
5. Testing Multi-Tenant Systems
Use tools like Postman or Swagger to test your multi-tenant API endpoints. Ensure each tenant’s data is isolated and accessible only by the correct tenant.
What Undercode Say:
Building a multi-tenant system requires careful planning and implementation. EF Core provides powerful tools like dynamic connection strings and query filters to simplify this process. Always ensure tenant isolation by validating `TenantId` from headers or JWT claims. Use scoped `DbContext` instances to maintain data integrity during HTTP requests. For further reading, refer to the official EF Core documentation.
Related Commands and Tools:
- Linux Command: Use `curl` to test API endpoints with tenant-specific headers:
curl -H "TenantId: your-tenant-id" http://yourapi.com/endpoint
- Windows Command: Use `PowerShell` to test APIs:
Invoke-WebRequest -Uri "http://yourapi.com/endpoint" -Headers @{"TenantId"="your-tenant-id"}
- Database Command: Use SQL queries to verify tenant-specific data:
SELECT * FROM YourTable WHERE TenantId = 'your-tenant-id';
By following these steps and commands, you can effectively build and manage a multi-tenant system using EF Core.
References:
Reported By: Milan Jovanovic – Hackers Feeds
Extra Hub: Undercode MoN
Basic Verification: Pass ✅