Nano ASP.NET SaaS 模板
管理员凭据(所有租户):admin@email.com / Password123!
样本数据每小时重置一次

使用 Entity Framework Core 和 ASP.NET 构建多租户应用程序——免费指南(第 1 部分)

瑞安·刘易斯
2023年5月29日

在软件开发人员的职业生涯中,总会有一段时间,他们开始考虑构建一个“软件即服务”(SaaS)类型的平台。一个 SaaS 这种商业模式是:订阅用户付费使用该应用程序,每位用户都有自己的独立实例,这使得开发者(你)能够提前退休,搬到塔希提岛的一处僻静海滩,靠被动收入生活。.

从技术角度来看,实现这种商业模式最快、最粗糙的方法是为主机用户分别创建独立的部署环境。然而,这种做法并不理想,因为一旦客户数量超过寥寥数人,维护这些独立的部署环境很快就会变成一场噩梦。.

现实来看,要想实现你在南太平洋提前退休的梦想,唯一的方法就是采取一种被称为 多租户架构. 多租户是指仅有一个应用程序实例即可为多个订阅者提供服务 (租户), ,但其实现方式确保了每个租户的数据完全隔离

在本文中,我们将探讨如何通过……来实现这种多租户SaaS架构。 ASP.NET 和 Entity Framework Core. 我们将一步步构建一个简单的应用程序。完成本教程后,您将了解 ASP.NET 中多租户机制的基本原理。.

下载 GitHub 上的最终版本在此

此外还有一个 第二部分 在本文的这一部分,我们将扩展此单数据库配置的功能,以支持混合型和多数据库配置

虽然这篇文章是理解多租户架构的绝佳途径,但要编写出一个安全且架构良好的、包含身份认证功能的最终解决方案,确实颇具挑战。该 Nano ASP.NET 模板 该项目遵循了您将在这里学到的相同基础原理,但额外加入了 ASP Identity、Clean Architecture,以及构建应用程序所需的各类控制器和服务。与其花费数小时去实现用户管理、授权、身份验证、密码重置等琐碎的基础功能,不如直接参考现成的模板代码,尽早开始编写应用程序的核心业务逻辑。.

从宏观层面来看,实现多租户有两种架构:

  • 单一数据库——租户列分离
  • 多数据库——每个租户一个数据库

第一种方法,, 单一数据库, 为所有租户使用一个数据库,并实现了 租户ID 列来将数据分隔开。乍一看,将不同数据混在同一个表中似乎是件疯狂的事,但这实际上是实现多租户的最常见方法。借助 Entity Framework 的强大功能以及 全局查询过滤器, 这种方法效果很好,而且实现起来其实并不复杂。.

如果您的业务需求允许,我建议采用“单一数据库”方案。当然,如果您有法律要求规定客户数据必须完全隔离,那么“多数据库”方案可能是唯一的选择。 无法采用单数据库方案的另一个可能原因是,您的客户可能使用Power BI等外部工具,而这些工具需要直接连接到数据库。在这种情况下,无法允许他们访问包含共享数据的数据库。.

第二种方法,, 多个数据库, ,即每个租户都有自己的数据库。在这两种方法中,第一步都是根据每个请求识别相应的租户。而“每个租户一个数据库”的方法更进一步,会查询该租户的连接字符串,并在进行数据访问时使用该连接字符串。采用“每个租户一个数据库”的方法,其优势在于每个租户的数据都完全隔离。.

虽然完全的数据隔离乍看之下似乎很理想,但在需要创建新租户或执行模式更新时,就会带来额外的复杂性。 (移民). 对于新租户,您需要与 Azure 或 AWS 等基础设施提供商配合,实现某些自动化流程,以便在创建新租户时自动部署新的数据库。另一个问题是数据迁移,即每当您对数据库应用新更改时,都需要对所有租户数据库执行迁移操作。.

最后,需要注意的是,可以进行一项 混合型 混合方案。混合方案是指将大部分租户存储在主数据库中,同时为有特殊需求的租户设置独立的数据库。如果某些租户需要更强的数据隔离性或更高的性能,这种方案可能会有所帮助,但它确实带来了多数据库方案所固有的复杂性。.

在本教程中,我们将使用一个数据库实现多租户功能,并通过以下方式确保租户隔离: 租户ID 专栏。你在现实生活中用过的绝大多数SaaS应用,比如CRM、项目管理应用、POS系统等,都采用单一数据库。单一数据库的方案更易于维护,而如果我们真想在塔希提岛享受提前退休的生活,易于维护这一点至关重要。.

我们将构建一个不带任何用户界面的 Web API,其中包含多租户应用程序的核心要素。.

从宏观层面来看,主要有 使多租户模式得以运行的三个关键要素。.

  • 每次请求的租户标识
  • 确保所有数据都标有 TenantId
  • 按 TenantId 过滤所有请求

在本教程中,我们将逐一讲解这些要点,首先从根据每个请求识别租户开始。. 

解开这个难题的第一步是根据每项请求识别租户。由于 中间件 它会在每个请求中运行,并在到达任何端点之前被触发,因此是筛选出一个 租户ID 来自传入的请求。.

您还可以通过其他方式呈现该 租户ID 在您的请求中,其中有两项特别重要:

  • 请求头
  • 令牌/Cookie 声明

为简便起见,在本教程中我们将使用 请求头 为所有请求识别租户,但在实际应用中,您通常只会通过请求头来识别特定请求的租户。 未经身份验证 请求。您可能需要使用 令牌/Cookie 声明 适用于所有人 已验证 此后的请求。换句话说,只有当用户尝试登录时,我们才会检查请求头中的租户 ID。一旦用户获得了令牌/Cookie,租户 ID 就会包含在该令牌/Cookie 中,并作为身份验证凭据的一部分随每次请求一并发送。. 

需要注意的是,在本教程中,我们将不会实现任何身份验证或授权机制。本教程旨在演示多租户架构的基本概念。一旦 ASP 身份 一旦将这一因素加入其中,情况就会变得稍微复杂一些。该 Nano ASP.NET 模板 不过,它确实实现了授权和身份验证。如果你想了解如何保障多租户应用程序的安全,这绝对是一份不可多得的资源。.

让我们开始编写一些代码吧。我们可以先创建一个 Web API 项目。一个 Web API 项目仅包含 REST 端点, ,而且这里没有任何类似用户界面的东西——取而代之的是,我们将使用 邮差 用于与我们的多租户应用程序进行交互和测试。请选择最新的 .NET 框架(截至本文撰写之时为 .NET 7),并选择 无 用于身份验证选项。.

我们正在创建的项目将包含一个名为 产品, ,其中有一项服务名为 产品与服务, ,以及一个名为 ProductsController. 其实根本没必要创建一个 Product 服务——我们完全可以将所有业务逻辑都放在 Products 控制器中,但采用服务模式并结合依赖注入是一种良好的编程实践。我之前发表过其他文章对此进行了说明 接口 和 依赖注入.

接下来的步骤将侧重于搭建一个具备 CRUD 功能的基础应用程序。稍后,我们将把这个熟悉的单租户应用程序改造为多租户应用程序。.

我们将首先添加必要的 Nuget 适用于 Entity Framework. 在 解决方案资源管理器 并选择 管理 NuGet 包. 我们需要安装三个:

  • Entity Framework Core
  • Entity Framework SQL Server
  • Entity Framework 工具

接下来,创建一个 模型 文件夹,并创建一个名为 ApplicationDbContext. 该类应继承自 DbContext 该类由 Entity Framework Core NuGet 包提供。稍后,我们将在 ApplicationDBContext 中添加一个 currentTenant 服务。此时,代码应如下所示。.

public 类 ApplicationDbContext : DbContext
{

        // 构造函数——Entity Framework 采用的约定 
        public ApplicationDbContext(DbContextOptions 选项) : 基数(选项)
        {
        }
  
}

在 appsettings.json 文件中,为连接字符串创建一个条目,并将其命名为“默认连接”,如下所示:

  "连接字符串": {
    "默认连接": "数据源=(localdb)\\mssqllocaldb;Database=multiTenantAppDb;Trusted_Connection=True;MultipleActiveResultSets=true"
  },

在 program.cs 添加以下代码行,将数据库连接作为服务添加到应用程序中:

// 添加一个带有配置的数据库服务——连接字符串从 appsettings.json 中读取
构建者.服务.AddDbContext<ApplicationDbContext>(选项 => 选项.UseSqlServer(构建者.配置.GetConnectionString("默认连接")));

对于任何配置为使用 Entity Framework 连接数据库的应用程序来说,这都是标准代码。稍后,我们将生成一个初始迁移,并创建一个名为 multiTenantAppDb.

在 模型 文件夹中,创建一个名为 IMustHaveTenant 具有一个属性,, 租户ID 作为一个 字符串. 这个简单的接口将作为我们希望实现租户隔离的任何实体的标记。它将使我们能够遍历应用程序中所有租户隔离的实体,并确保它们都包含一个 租户ID 属性。.

public 接口 IMustHaveTenant
{
    public 字符串 租户ID { get; set; }
}

在 模型 文件夹中,创建一个名为 产品 该类实现了 IMustHaveTenant 接口。将其中一个字段设为 字符串 名为 租户ID. 为了便于理解,我们将为租户生成诸如‘alpha’、‘beta’、‘gamma’之类的ID。Product类应如下所示:

public 类 产品 : IMustHaveTenant
{
    public int Id { get; set; }
    public 字符串 姓名 { get; set; }
    public 十进制 价格 { get; set; }
    public 字符串 租户ID { get; set; }
}

让我们记得创建一个 DbSet 对于我们位于 ApplicationDbContext 如下所示:

    public DbSet<产品> 产品 { 获取; set; }

我们将回到 ApplicationDbContext 这些内容我们稍后再谈,现在先专注于搭建一个可运行的应用程序。.

在同一 模型 文件夹中,创建另一个名为 租户 具有以下属性。该 Tenant 实体与应用程序中的其他任何实体之间均不存在任何关系。此外,我们不会专门为管理租户而创建服务或控制器,因为这并非本教程的重点。 取而代之的是,我们将直接在数据库中手动创建这些实体。我们将手动为主键赋值字符串,因此请在 ID 属性中添加包含数据注解的以下代码:

public 类 租户
{
    [关键]
    [数据库生成(数据库生成的选项.无)]
    public 字符串 Id { get; set; }
    public 字符串 姓名 { get; set; }
}

创建一个 DbSet 对于我们位于 ApplicationDbContext:

    public DbSet<租户> 租户 { 获取; set; }

创建一个名为 服务 位于应用程序的顶级目录下,该文件夹内还有一个名为 产品与服务. 在这里,我们将创建一个名为 产品与服务 以及一个名为 IProductService 像这样:

public 接口 IProductService
{
    IEnumerable<产品> 获取所有产品();
    产品 GetProductById(int id);
    产品 CreateProduct(CreateProductRequest 请求);
    bool 删除产品(int id);
}

上文是 接口, ,以下是 服务 其中包含用于管理产品的业务逻辑

public 类 产品与服务 : IProductService
{
    私有 只读 ApplicationDbContext _context; // 数据库上下文
    public 产品与服务(ApplicationDbContext context)
    {
        _context = 上下文;
    }

    // 获取所有产品的列表
    public IEnumerable<产品> 获取所有产品()
    {
        var 产品 = _context.产品.ToList();
        返回 产品;
    }

    // 获取单个商品
    public 产品 GetProductById(int id)
    {
        var 产品 = _context.产品.在哪里(x => x.Id == id).FirstOrDefault();
        返回 产品;
    }

    // 创建一个新产品
    public 产品 CreateProduct(CreateProductRequest 请求)
    {
        var 产品 = 新 产品();
        产品.姓名 = 请求.姓名;
        产品.价格 = 请求.价格;

        _context.添加(产品);
        _context.SaveChanges();

        返回 产品;
    }


    // 删除一个产品
    public bool 删除产品(int id)
    {
        var 产品 = _context.产品.在哪里(x => x.Id == id).FirstOrDefault();

        如果 (产品 != null)
        {
            _context.删除(产品);
            _context.SaveChanges();
            返回 true;
        }
        返回 false;
    }
}

对于 创建 方法,创建一个 DTO (数据传输对象)类,用于处理新产品请求。在此情况下,我将该类命名为 CreateProductRequest 并将其放入一个 DTOs 文件夹 在……内 产品与服务 文件夹,如下所示:

    public 类 CreateProductRequest
    {
        public 字符串 姓名 { get; set; }
        public 十进制 价格 { get; set; }
    }

接下来,我们需要在顶级 program.cs 类作为 临时服务. 我们已经将数据库配置为使用 ApplicationDBContext 与 SqlServer 以及在以下位置指定的连接字符串: appsettings.json. 此时,program.cs 类的代码应如下所示:

使用 微软.EntityFrameworkCore;
使用 queryFilterApp.模型;
使用 queryFilterApp.服务.产品与服务;

var 构建者 = WebApplication.CreateBuilder(args); // <--- 1. 创建构建器(ASP.NET 惯例)

// 创建'Web API 项目'模板时添加的默认服务
构建者.服务.AddControllers();
构建者.服务.AddEndpointsApiExplorer();

// 添加一个带有配置的数据库服务——连接字符串从 appsettings.json 中读取
构建者.服务.AddDbContext<ApplicationDbContext>(选项 => 选项.UseSqlServer(构建者.配置.GetConnectionString("默认连接")));

// 添加我们自己的服务——CRUD 服务应以“transient”生命周期进行注册
构建者.服务.AddTransient<IProductService, 产品与服务>();


var app = 构建者.构建(); // <--- 2. 构建应用程序(ASP.NET 规范)


// 选择'创建 Web API 项目'时的默认中间件'
app.使用HTTPS重定向(); 
app.使用授权(); 
app.MapControllers();

app.运行(); // <--- 3. 运行应用程序(ASP.NET 惯例)

最后,我们将创建一个 Products 控制器,其中包含 获取, 帖子, ,以及 删除 端点。控制器将注入 Product 服务的实例,这与 ASP.NET 应用程序中的常规做法一致。 截至目前,除了创建 Tenant 表之外,所有操作都是设置基本 ASP.NET 应用程序的标准流程。我们应该运行该应用程序以确保一切按预期运行,因为在接下来的步骤中,我们将使其支持多租户。.

    [路线("api/[控制器]")]
    [ApiController]
    public 类 ProductsController : ControllerBase
    {
        私有 只读 IProductService _productService; 

        public ProductsController(IProductService productService)
        {
            _productService = productService; // 注入产品服务
        }
   
        // 获取产品列表
        [HttpGet]
        public IActionResult 获取()
        {   
            var 列表 = _productService.获取所有产品(); 
            返回 好的(列表);
        }

        // 创建一个新产品
        [HttpPost]
        public IActionResult 帖子(CreateProductRequest 请求)
        {
            var 结果 = _productService.CreateProduct(请求);
            返回 好的(结果);
        }

        // 按 ID 删除商品
        [HttpDelete("{id}")]
        public IActionResult 删除(int id)
        {
            var 结果 = _productService.删除产品(id);
            返回 好的(结果);
        }

    }

在运行应用程序之前,我们需要 创建初始迁移 并运行该 更新数据库 用于实际创建数据库和表的命令。请注意,如果您从 GitHub 下载示例项目,初始迁移已创建完毕,您只需运行 更新数据库 命令在 包管理器控制台.

打开 SQL Server Management Studio (SSMS) 或 数据库资源管理器 在 Visual Studio 中查看数据库。如果一切正常,应该会出现一个名为 multiTenantAppDb 用一个 产品 表和一个 租户 表格。.

Multi-Tenant App with Entity Framework

在 tenants 表中创建几个租户。在真正的多租户应用程序中,您当然会创建一个服务和一个带有 CRUD 方法的控制器,以便通过 API 管理租户。为了节省时间并简化操作,我们将手动添加租户。如果您计划构建一个多租户应用程序,那么 Nano ASP.NET 模板 包含了与基于角色的租户和用户管理相关的所有内容。.

Multi-Tenant App ID

首先,在应用程序中创建一个名为 中间件. 然后创建一个名为 TenantResolver. 当一个类遵循特定的签名时,它就成为中间件。中间件的签名是通过传递一个 RequestDelegate 构造函数中的参数。.

运行的代码包含在 任务 InvokeAsync 以下是该方法,就我们而言,Tenant Resolver 中间件的代码将如下所示:

    public 类 TenantResolver
    {
        私有 只读 RequestDelegate_next;
        public TenantResolver(RequestDelegate 下一项)
        {
            _下一页 = 下一页;
        }

        // 从传入的请求中获取租户 ID 
        public async 任务 InvokeAsync(HttpContext context, ICurrentTenantService currentTenantService)
        {
            上下文.请求.标题.TryGetValue("租户", out var tenantFromHeader); // 来自传入请求头中的租户 ID
            如果 (字符串.IsNullOrEmpty(tenantFromHeader) == false)
            {
                等待 currentTenantService.SetTenant(tenantFromHeader);
            }

            等待 _下一页(上下文);
        }


    }

该 HttpContext object 是一个包含有关传入请求信息的对象,我们将利用它来读取请求头值。该 currentTenantService 这是一个作用域服务,我们将在下一步中创建它,该服务负责在数据库中查询租户以验证其是否存在。它还将保存 tenantId 在请求生命周期中的整个过程中。.

在上面的代码中,我们使用了 TryGetValue 该方法用于检查请求中是否包含名为“tenant”的请求头;如果包含,则读取该值并尝试将其设置到 currentTenantService 中。.

如果您正在开发一个带有身份验证功能的安全应用程序,在尝试从请求头中读取数据之前,务必先从 Cookie 或 JWT 令牌中读取租户值。.

议程上的下一项是创建一个 CurrentTenantService 类和一个 ICurrentTenantService 接口。这是租户解析中间件将依赖的服务,用于验证租户是否存在于数据库中,并存储当前的租户值。该服务将在每次请求时被调用。由于租户值需要在整个请求生命周期内始终可用,因此应将此服务注册到一个 作用域生命周期.

在“services”文件夹中,创建一个名为 CurrentTenantService. 代码应如下所示:

public 类 CurrentTenantService : ICurrentTenantService
    {
        私有 只读 TenantDbContext _context;
        public 字符串? 租户ID { get; set; }

        public CurrentTenantService(TenantDbContext 上下文)
        {
            _context = 上下文;

        }
        public async 任务<bool> SetTenant(字符串 租户)
        {

            var 租户信息 = 等待 _context.租户.在哪里(x => x.Id == 租户).FirstOrDefaultAsync(); // 检查租户是否存在
            如果 (租户信息 != null)
            {
                租户ID = 租户;
                返回 true;
            }
            else
            {
                throw简体中文(大陆) 新 异常("租户无效"); 
            }

        }
    }

下面就是 接口 应显示为:

    public 接口 ICurrentTenantService
    {
        字符串? 租户ID { get; set; }
        public Task<bool> SetTenant(字符串 租户);
    }

该服务有一个方法,该方法接受一个字符串值——即 租户密钥, ,并在数据库中查询该租户以验证其是否存在。在实际应用中,您可能还需要检查该租户是否拥有有效的订阅、其会员等级等。如果该租户存在,则将该值存储为 租户ID 该属性在请求生命周期内始终可用,且可在应用程序的任何其他位置访问——最重要的是,在 ApplicationDbContext.

正如我们将在接下来的步骤中看到的,该服务是在 ApplicationDbContext 以及 租户ID 每次向数据库保存数据时,都会读取该属性。现在,考虑到该 CurrentTenantService 需要一个上下文类来在数据库中查询租户,并且该 ApplicationDbContext 将调用 CurrentTenantService 每次构建时,如果尝试使用它,就会出现循环逻辑错误 ApplicationDbContext 在 CurrentTenantService.

仔细看看该代码的 CurrentTenantService 你会注意到,我们正在使用一个名为 TenantDbContext 以访问数据库。通过在请求开始时为查询租户创建一个独立的上下文,我们可以避免循环逻辑错误。顺便提一下,其他关于构建多租户应用的教程很少会解释这一点,因为其中大多数都没有展示如何将租户信息存储在数据库中。 既然我们肯定希望将租户信息存储在数据库中,而不是存储在 JSON 文件之类的文件里,那就来创建 TenantDbContext.

We’ll need to create a separate context class for looking up tenant info as the requests come in. This context class will only contain one DbSet, 租户, and will not invoke any services in its constructor. So in other words, its a very basic context! Here’s how the code should look:

  public 类 TenantDbContext : DbContext
    {
        // 该上下文用于在收到请求时查询租户。.
        public TenantDbContext(DbContextOptions<TenantDbContext> 选项)
        : 基数(选项)
        {
        }

        public DbSet<租户> 租户 { get; set; }

    }

Now that our project contains multiple context classes, we will need to take some extra steps when running 移民 and applying database changes. When you run the 添加迁移 或 更新数据库 commands in 包管理器控制台, you’ll need to specify which context to use. Just write -Context ApplicationDbContext after the commands like this:

添加-迁移 -上下文 ApplicationDbContext
更新-数据库 -上下文 ApplicationDbContext

TenantDbContext will not be used for migrations, for migrations we’ll use the main context, ApplicationDbContext. When adding new entities, you should only add the DbSets 到 ApplicationDbContext – TenantDbContext only needs to be aware of the 租户 表格。.

At this point, we have completed the first piece of the puzzle in building a multi-tenant application. For every incoming request, our middleware is reading a tenant value from the request header and storing that value in our CurrentTenantService.

The place we need to use that current 租户ID is in the ApplicationDbContext. When we are saving entities, we will write that value to the entity being saved if the entity is of type IMustHaveTenant. This is the second piece of the puzzle and it looks like this:

public 类 ApplicationDbContext : DbContext
    {
        私有 只读 ICurrentTenantService _currentTenantService;
        public 字符串 当前租户ID { get; set; }

        // 构造函数 
        public ApplicationDbContext(ICurrentTenantService currentTenantService, DbContextOptions<ApplicationDbContext> 选项) : 基数(选项)
        {
            _currentTenantService = currentTenantService;
            当前租户ID = _currentTenantService.租户ID;
        }

        // DbSets -- 为所有将由 EF 管理的实体类型创建
        public DbSet<产品> 产品 { get; set; }
        public DbSet<租户> 租户 { get; set; }

        // 保存更改时——将租户 ID 写入表中
        public 覆盖 int SaveChanges()
        {        
            foreach (var 条目 在 ChangeTracker.条目<IMustHaveTenant>().ToList()) 
            {
                开关 (条目.州)
                {
                    案例 EntityState.已添加:
                    案例 EntityState.已修改:
                        条目.实体.租户ID = 当前租户ID; 
                        break;
                }
            }
            var 结果 = 基数.SaveChanges();
            返回 结果;
        }
    }

The first important change is to instantiate the CurrentTenantService in the constructor of ApplicationDbContext. We will also read the 租户ID property of that service in the constructor, and store it as a local value in ApplicationDbContext.

Next, we will add an 覆盖 到 SaveChanges method. The code here is checking for any entities that are of type IMustHaveTenant, and writing the current 租户ID value for those entities whenever they are saved or modified.

Using a marker interface like IMustHaveTenant is especially useful in a case like this because all we have to do is implement that interface on any entity we want to be tenant isolated. You could have some entities that are not tenant isolated like static data (country lists for example) and these entities will not be subjected to any on save changes automation.

Now all will need to do is add a 在哪里 clause like x=>x.TenantId == currentTenantService.TenantId anywhere we have a 获取 request, right? We’ll also need to instantiate the currentTenantService in every controller with a get statement, right? Thankfully no, that would be extremely uncool and repetitive. The answer is that there is a better way called global query filtering, which we will implement next.

For the final piece of the puzzle, we want to filter every query whenever we read data. At this point, we can guarantee that any entity of type IMustHaveTenant will have a 租户ID column with a value of the tenant that created it.

In order to avoid the repetitive madness of adding Where clauses everywhere, we will add an OnModelCreating override method in ApplicationDbContext and use a Query Filter. The final rendition of the ApplicationDbContext code should look as follows:

public 类 ApplicationDbContext : DbContext
    {
        私有 只读 ICurrentTenantService _currentTenantService;
        public 字符串 当前租户ID { get; set; }

        // 构造函数 
        public ApplicationDbContext(ICurrentTenantService currentTenantService, DbContextOptions<ApplicationDbContext> 选项) : 基数(选项)
        {
            _currentTenantService = currentTenantService;
            当前租户ID = _currentTenantService.租户ID;
        }

        // DbSets -- 为所有将由 EF 管理的实体类型创建
        public DbSet<产品> 产品 { get; set; }
        public DbSet<租户> 租户 { get; set; }

        // 关于模型创建——多租户查询过滤器 
        受保护的 覆盖 void OnModelCreating(ModelBuilder 构建器)
        {         
            构建者.实体<产品>().HasQueryFilter(a => a.租户ID == 当前租户ID); 
        }

        // 保存更改时——将租户 ID 写入表中
        public 覆盖 int SaveChanges()
        {        
            foreach (var 条目 在 ChangeTracker.条目<IMustHaveTenant>().ToList()) 
            {
                开关 (条目.州)
                {
                    案例 EntityState.已添加:
                    案例 EntityState.已修改:
                        条目.实体.租户ID = 当前租户ID; 
                        break;
                }
            }
            var 结果 = 基数.SaveChanges();
            返回 结果;
        }
    }

该 OnModelCreating method fires only once, at the time of the application launch. While the model itself is static, the value of 当前租户ID will remain dynamic. In other words, anytime a query is performed, the value of 当前租户ID will be of the current request.

Just like that, we have implemented the third and final piece of the puzzle. You now have a multitenant application. Whenever you add new entities, you’ll need to implement the IMustHaveTenant interface on them to make them tenant isolated. You’ll also have to add another query filter in the OnModelCreating model because you cannot specify an interface type here.

You could create a fancy extension method to automate the process of adding query filters based on interface type, but that is outside of the scope of this tutorial. Check out the Nano ASP.NET 模板 though if that sounds interesting. The Nano ASP.NET Boilerplate contains an extension method to query filters based on interface type as well as many other useful methods.

At this point the application is complete and we can move on to testing what we’ve created.

打开 邮差 or whatever tool you wish to use for testing and start by creating a few Products. In the 标题 section of the request, create a header called 租户 and populate the value with one of the tenantIds you created earlier. Here I will create a few products as the beta tenant:

Multi-Tenant App Headers

Above, the header value and below, the Post body:

Multi-Tenant App Body

After you create a few products for each tenant, the database 产品 table will look like this

Multi-Tenant App Products table

该 租户ID field should be populated with the values of the tenant that created them. Now when we go to retrieve the list of products with a 获取 request, only the products that belong to the specified tenant should be returned. Create a 租户 header value, just like we did for the 帖子 request when we created the products, and send the 获取 request.

Alpha Tenant

Above, sending the 获取 request for the alpha tenant. Below, sending the get request for the beta tenant:

Beta Tenant

You should see tenant specific lists of products if everything is working properly. So, if you’ve made it this far congratulations, because you now understand the fundamentals of creating a multi-tenant application with ASP.NET 和 Entity Framework Core. You have a big step towards building your SaaS app and living the easy life in Tahiti.

If you found this article helpful and want to take it to the next level, you could try to implement authorization 和 authentication to make it a secure multi-tenant application. As it is now, anyone can change the request header. When you use something like ASP 身份 to issue tamper-proof cookies or tokens, you would store the tenant value within those and can reliably validate which tenant is making the request.

在 第二部分 of this tutorial series, we will extend this solution to support hybrid and multiple tenant databases.

Please consider buying the Nano ASP.NET SaaS boilerplate to kickstart your next multi-tenant project! You will be supporting this blog and saving yourself a lot of time, even if its just to use as a learning resource. Good luck on whatever path you choose.

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

需要一个 ASP.NET 模板来构建您的下一个 MVP 吗?
快来看看这个 Nano ASP.NET 多租户 SaaS 模板项目,为您节省数周甚至数月的开发时间。.
了解更多