Sponsor: Do you build complex software systems? See how NServiceBus makes it easier to design, build, and manage software systems that use message queues to achieve loose coupling. Get started for free.There are many different ways to handle multi-tenancy. This blog post will cover one approach to EF Core Multi-Tenancy that will work if you are using a shared database approach, meaning you use the same database for multiple tenants, that are disambiguated using tenant ID column. If you want more details on Multi-Tenancy, check out the Microsoft Docs on the topic, related to designing multi-tenant apps using Azure SQL Database.
EntityLet’s jump right into some sample code of a simple Entity that represents a customer. Notice the
FilterThe approach we are going to use is to pre-filter any
DbContext. We can do this by using the EntityFramework-Plus package. It provides us the ability to specify per context instance how to pre-filter our DbSets. We can do this by adding our
TenantIdas a ctor parameter and use the
Example UsageHere’s a small console app that adds two new customer records both with the same
CustomerId = 1. When creating the
MyDbContext, we the
TenantIdwe want to pre-filter on.