EF core (code first) 经过自定义 Migration History 实现多租户使用同一数据库时更新数据库结构

前言

写这篇文章的缘由,其实因为我写EF core 实现多租户的时候,遇到的问题。html

具体文章的连接:git

Asp.net core下利用EF core实现从数据实现多租户(1)github

Asp.net core下利用EF core实现从数据实现多租户(2) : 按表分离   (主要关联文章)sql

这里我遇到的最主要问题是:因为多租户的表使用的是同一个数据库。因为这个缘由,没法经过 Database.EnsureCreated() 自动建立多个结构相同但名字不一样的表。数据库

因此我在文中提到,须要本身跑脚本去建立多有的表。app

虽然我依然认为在多租户的状况下使用sql管理表是更可靠的方案,但若是能够利用EF core原生提供的Migration机制,在运行时自动建立和更新数据表结构,那更加友好。ide

 

实现的思路函数

其实咱们都知道,EF core (code first) 会在数据库中生成惟一一个 __EFMigrationHistory 表,数据库的版本记录在这里。post

在咱们文章的场景下,因为有多个租户同时使用,同一个表结构(Products)会出现屡次,那么意思就是一个 __EFMigrationHistory 没法同时记录多个租户的数据表版本。ui

好了,既然问题的关键已经知道了,咱们能够在这里先把答案揭晓,在下问在详细说明实现方法:

图中能够看到,咱们自定义MigrationHistory表,而且在一个数据下,同时出现了store1和store2的 MigrationHistory 表。

 

 

 

实施

项目介绍

这是一个多租户系统,具体来讲就是根据不一样的租户,建立相同的全部数据表。

 

项目依赖:

1. .net core app 3.1。在机器上安装好.net core SDK, 版本3.1

2. Mysql. 使用 Pomelo.EntityFrameworkCore.MySql 包

3. EF core,Microsoft.EntityFrameworkCore, 版本3.1.1。这里必需要用3.1的,由于ef core3.0是面向.net standard 2.1.  

4. EF core design, Microsoft.EntityFrameworkCore.Design, 版本 3.1.1

5. dotnet-ef tool, 版本 3.1.1

 

关键的对象:

1. MigrationsAssembly, 利用此类去实现建立对应的Migration单元。

2. Migration files, 这里指的是一批Migration相关的文件,利用执行dotnet-ef 命令生成具体的文件,从而真正地去建立和更新数据库。

 

实施步骤

1. 运行dotnet-ef命令,生成Migration files

命令:

1 dotnet-ef migrations add init

执行后,会在项目中的Migrations文件夹下生成多个*.cs文件,其实他们也是可执行C#对象

机构以下:

 

 

这3个文件中,主要起做用的是*_init.cs这个文件

打开以后咱们须要对他进行修改

 1 using Microsoft.EntityFrameworkCore.Metadata;
 2 using Microsoft.EntityFrameworkCore.Migrations;
 3 
 4 namespace kiwiho.Course.MultipleTenancy.EFcore.Api.Migrations
 5 {
 6     public partial class init : Migration
 7     {
 8         private readonly string prefix;
 9         public init(string prefix)
10         {
11             if (string.IsNullOrEmpty(prefix))
12             {
13                 throw new System.ArgumentNullException();
14             }
15             this.prefix = prefix;
16         }
17 
18         protected override void Up(MigrationBuilder migrationBuilder)
19         {
20             migrationBuilder.CreateTable(
21                 name: prefix + "_Products",
22                 columns: table => new
23                 {
24                     Id = table.Column<int>(nullable: false)
25                         .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn),
26                     Name = table.Column<string>(maxLength: 50, nullable: false),
27                     Category = table.Column<string>(maxLength: 50, nullable: true),
28                     Price = table.Column<double>(nullable: true)
29                 },
30                 constraints: table =>
31                 {
32                     table.PrimaryKey("PK__Products", x => x.Id);
33                 });
34         }
35 
36         protected override void Down(MigrationBuilder migrationBuilder)
37         {
38             migrationBuilder.DropTable(
39                 name: prefix + "_Products");
40         }
41     }
42 }
init migration

这里修改的主要是:

 1.1 新增构造函数,而且在里面添加一个 prefix 参数。

 1.2 在Up方法中,对table Name进行修改,把prefix变量加在_Product前面(第21行)

 1.3 在Down方法中,对table Name进行修改,把prefix变量加在_Product前面 (第39行)

 

2. 建立 MigrationByTenantAssembly 文件。

因为上一步讲Migration file的构造函数修改了,理论上EF core已经五法经过默认的方式成功执行改Migration file了

 1 using System;
 2 using System.Reflection;
 3 using Microsoft.EntityFrameworkCore;
 4 using Microsoft.EntityFrameworkCore.Diagnostics;
 5 using Microsoft.EntityFrameworkCore.Infrastructure;
 6 using Microsoft.EntityFrameworkCore.Migrations;
 7 using Microsoft.EntityFrameworkCore.Migrations.Internal;
 8 
 9 namespace kiwiho.Course.MultipleTenancy.EFcore.Api.Infrastructure
10 {
11     public class MigrationByTenantAssembly : MigrationsAssembly
12     {
13         private readonly DbContext context;
14 
15         public MigrationByTenantAssembly(ICurrentDbContext currentContext,
16               IDbContextOptions options, IMigrationsIdGenerator idGenerator,
17               IDiagnosticsLogger<DbLoggerCategory.Migrations> logger)
18           : base(currentContext, options, idGenerator, logger)
19         {
20             context = currentContext.Context;
21         }
22 
23         public override Migration CreateMigration(TypeInfo migrationClass,
24               string activeProvider)
25         {
26             if (activeProvider == null)
27                 throw new ArgumentNullException($"{nameof(activeProvider)} argument is null");
28 
29             var hasCtorWithSchema = migrationClass
30                     .GetConstructor(new[] { typeof(string) }) != null;
31 
32             if (hasCtorWithSchema && context is ITenantDbContext tenantDbContext)
33             {
34                 var instance = (Migration)Activator.CreateInstance(migrationClass.AsType(), tenantDbContext?.TenantInfo?.Name);
35                 instance.ActiveProvider = activeProvider;
36                 return instance;
37             }
38 
39             return base.CreateMigration(migrationClass, activeProvider);
40         }
41     }
42 }
MigrationByTenantAssembly

 

这个类中没有什么特别的,关键在于29~37行。首先须要判断目标 Migration 对象的是否有一个构造函数的参数有且仅有一个string 类型

判断DbContext是否有实现ITenantDbContext接口。

利用 Activator 建立 Migration 实例(把tenant Name传进构造函数)

 

3. 在 MultipleTenancyExtension 类的AddDatabase方法中,添加自定义MigrationHistory表名

 1 var dbOptionBuilder = options.UseMySql(resolver.GetConnection(), builder =>
 2 {
 3     if (option.Type == ConnectionResolverType.ByTabel)
 4     {
 5         builder.MigrationsHistoryTable(${tenantInfo.Name}__EFMigrationsHistory");
 6     }
 7 });
 8 
 9 
10 dbOptionBuilder.ReplaceService<Microsoft.EntityFrameworkCore.Migrations.IMigrationsAssembly, MigrationByTenantAssembly>();

最关键的一点是第5行,调用 MigrationsHistoryTable 设置MigrationHistory表名

另一点是第10行,用 MigrationByTenantAssembly 类替换 EF core 中默认的实现(IMigrationsAssembly接口)

 

4. 在ProductController的构造函数中,修改为以下

Database.Migrate 的做用主要是在运行时能够执行数据库的建立和更新

1 public ProductController(StoreDbContext storeDbContext)
2 {
3     this.storeDbContext = storeDbContext;
4     this.storeDbContext.Database.Migrate();
5 }

 

 

查看效果

调用接口

跟系列文章同样,咱们先调用建立product的接口分别在store1和store2中添加记录。

下面是store1 的查询结果

 

store2的查询结果

 

 

 

 查看数据库验证数据

数据库的表结构

 

 

store1_Products 表数据

 

 

store2_Products 表数据

 

 

 

总结

本文中咱们介绍了ef core 的code first模式下是如何更新数据库的,而且经过添加 Migration 对象的构造函数 ,自行添加了必要参数。

经过替换EF core中默认的 IMigrationsAssembly 实现, MigrationByTenantAssembly 中自定对Migration对象实例化。

替换EF core中默认的MigrationHistory最终实现需求。

 

本文虽然只是一个示例,可是却能够在真实项目中使用相同的手段以实现需求。不过仍是那句话,对于多租户状况下,我推荐使用db first模式。

 

关于代码

代码已经传上github,请查看EF_code_first的分支的代码。

https://github.com/woailibain/EFCore.MultipleTenancyDemo/tree/EF_code_first

相关文章
相关标签/搜索