EF core (code first) 通过自动迁移实现多租户数据分离 :按Schema分离数据

前言

本文是多租户系列文章的附加操作文章,如果想查看系列中的其他文章请查看下列文章

主线文章

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

Asp.net core下利用EF core实现从数据实现多租户(2) : 按表分离 

Asp.net core下利用EF core实现从数据实现多租户(3): 按Schema分离 附加:EF Migration 操作   (强关联文章,建议先阅读

 

附加文章

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

EF core (code first) 通过自动迁移实现多租户数据分离 :按Schema分离数据   (本文)

 

实施

项目介绍

本项目是用系列文章的主分支代码进行修改的。目前项目主要支持使用MySql,通过分库,分表实现多租户。

本文需要实现分Schema,MySql不能实现,所以引入了MSSqlServer。

 

项目依赖

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

2. Mysql. 使用 Pomelo.EntityFrameworkCore.MySql 包, 版本3.1.1  

3. MS Sql Server. 使用 Microsoft.EntityFrameworkCore.SqlServer 包,版本3.1.1  

4. EF core,Microsoft.EntityFrameworkCore, 版本3.1.1。这里必须要用3.1的,因为ef core3.0是面向.net standard 2.1.  

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

6. dotnet-ef tool, 版本 3.1.1

 

关键要点

其实如果读过我之前的EF core 自动迁移的文章,就会发现其实有几个关键点

1. 通过ef core CLI 生成Migration文件,并且在所有版本的Migration文件中添加一个带参数的构造函数

2. 自定义 MigrationByTenantAssembly 类,通过重写 CreateMigration 实现对修改后的Migration文件进行实例化

3. 自定义 __EFMigrationsHistory 的命名和存放位置

 

实施步骤

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

命令:

1 dotnet-ef migrations add init_schema

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

 

 

 

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

打开之后我们需要对他进行修改(所有修改内容已进行高亮)

这里修改的主要是:

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

 1.2 在Up方法中,对调用 EnsureSchema 进行修改,把 schema 变量加在name参数(第16行)

 1.3 在Up方法中,对调用 CreateTable 的 schema 参数中添加自定义变量schema (第20行)

 1.4 在Down方法中,对调用 DropTable 的 schema 参数中添加自定义变量schema(第39行)

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

 

 

2. 添加 MigrationByTenantAssembly 类,同时需要实现 MigrationsAssembly 类和重写 CreateMigration。

 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方法。(所有修改部分已经高亮) (这是非常关键的步骤)

关键点:

必须为 UseMySql 和 UseSqlServer 添加第二个参数,同时定义 __EFMigrationsHistory 的命名和存放位置。注意SqlServer中的schema命名必须跟dbContext中的schema的名字完全相同。由于MySql没有schema的概念,所以MySql中不能加入对应的schema参数。

在最后一行高亮的代码,通过 ReplaceService 替换 dbContext 中默认的 MigrationAssembly 实现类

 1 internal static IServiceCollection AddDatabase<TDbContext>(this IServiceCollection services,
 2         ConnectionResolverOption option)
 3     where TDbContext : DbContext, ITenantDbContext
 4 {
 5     services.AddSingleton(option);
 6 
 7     services.AddScoped<TenantInfo>();
 8     services.AddScoped<ISqlConnectionResolver, TenantSqlConnectionResolver>();
 9 
10     services.AddDbContext<TDbContext>((serviceProvider, options) =>
11     {
12         var dbContextManager = serviceProvider.GetService<IDbContextManager>();
13         var resolver = serviceProvider.GetRequiredService<ISqlConnectionResolver>();
14         var tenant = serviceProvider.GetService<TenantInfo>();
15 
16         DbContextOptionsBuilder dbOptionBuilder = null;
17         switch (option.DBType)
18         {
19             case DatabaseIntegration.MySql:
20                 dbOptionBuilder = options.UseMySql(resolver.GetConnection(),
21                     optionBuilder =>
22                     {
23                         if (option.Type == ConnectionResolverType.ByTabel)
24                         {
25                             optionBuilder.MigrationsHistoryTable($"{tenant.Name}__EFMigrationsHistory");
26                         }
27                     });
28                 break;
29             case DatabaseIntegration.SqlServer:
30                 dbOptionBuilder = options.UseSqlServer(resolver.GetConnection(),
31                     optionBuilder =>
32                     {
33                         if (option.Type == ConnectionResolverType.ByTabel)
34                         {
35                             optionBuilder.MigrationsHistoryTable($"{tenant.Name}__EFMigrationsHistory");
36                         }
37                         if (option.Type == ConnectionResolverType.BySchema)
38                         {
39                             optionBuilder.MigrationsHistoryTable("__EFMigrationsHistory", $"dbo.{tenant.Name}");
40                         }
41                     });
42                 break;
43             default:
44                 throw new System.NotSupportedException("db type not supported");
45         }
46         if (option.Type == ConnectionResolverType.ByTabel || option.Type == ConnectionResolverType.BySchema)
47         {
48             dbOptionBuilder.ReplaceService<IModelCacheKeyFactory, TenantModelCacheKeyFactory<TDbContext>>();
49             dbOptionBuilder.ReplaceService<Microsoft.EntityFrameworkCore.Migrations.IMigrationsAssembly, MigrationByTenantAssembly>();
50         }
51     });
52 
53     return services;
54 }

 

4. 修改StoreDbContext 中的 OnModelCreating 方法

1 protected override void OnModelCreating(ModelBuilder modelBuilder)
2 {
3     // seperate by table
4     // modelBuilder.Entity<Product>().ToTable(this.tenantInfo.Name + "_Products");
5     // seperate by Schema
6     modelBuilder.Entity<Product>().ToTable(nameof(this.Products), "dbo."+this.tenantInfo.Name);
7 }

 

5. 修改ProductController的构造函数

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

 

查看效果

1. 我们还是跟本系列的其他文章一样,分别在store1和store2中添加数据。

其中怎么添加的就不再重复贴图了,简单来说就是调用controller的post方法在数据库中添加数据

查询 store1 的数据

 

 

查询 store2 的数据

 

 

2. 查看数据库的机构和数据。

这是数据库的结构, 可以看到有4个schema,其中 dbo.store1 和 dbo.store2 是存放我们自己的数据的。

dbo.store1 和 dbo.store2 里面分别有一个__EFMigrationsHistory 表,这个就是EF core自动迁移的版本记录。

 

 

store1 中的数据

 

 store2 中的数据

 

 

添加迁移版本

读到这里的朋友可能还会有个疑问,觉得我这个自动迁移只做了一个版本,似乎不足以证明这个方案是可以行的。

1. 那我们就简单在Product里面再加一个 Discount 的字段。注意了,新加的字段我建议使用可空类型

 1 using System.ComponentModel.DataAnnotations;
 2 
 3 namespace kiwiho.Course.MultipleTenancy.EFcore.Api.DAL
 4 {
 5     public class Product
 6     {
 7         [Key]
 8         public int Id { get; set; } 
 9 
10         [StringLength(50), Required]
11         public string Name { get; set; }
12 
13         [StringLength(50)]
14         public string Category { get; set; }
15 
16         public double? Price { get; set; }
17 
18         public double? Discount { get; set; }
19     }
20 }

2. 通过dotnet-ef CLI运行命令,添加Migration版本

dotnet-ef migrations add disount_support

可以看到在Migrations 目录下多了2个*.cs文件

 

我们根据本文前面的步骤依样画瓢,分别添加带参数的构造函数和修改 Up 和 Down 方法

 1 using Microsoft.EntityFrameworkCore.Migrations;
 2 
 3 namespace kiwiho.Course.MultipleTenancy.EFcore.Api.Migrations
 4 {
 5     public partial class disount_support : Migration
 6     {
 7         private readonly string schema;
 8         public disount_support(string schema)
 9         {
10             this.schema = schema;
11         }
12 
13         protected override void Up(MigrationBuilder migrationBuilder)
14         {
15             migrationBuilder.AddColumn<double>(
16                 name: "Discount",
17                 schema: "dbo." + schema,
18                 table: "Products",
19                 nullable: true);
20         }
21 
22         protected override void Down(MigrationBuilder migrationBuilder)
23         {
24             migrationBuilder.DropColumn(
25                 name: "Discount",
26                 schema: "dbo." + schema,
27                 table: "Products");
28         }
29     }
30 }

 

我们启动项目,调用查询接口。然后在修改 store1 中的Coffee的Discount (这里注意的是,需要先调用接口,再到数据库中修改数据) 

下面就是 store1 的查询结果,可以看到Coffee的Discount是0.6 ,就会说咖啡是打六折的

 

 下面我们对比 store1 和 store2 的表结构和数据。发现 store2 中并没有Discount的字段。并且 __EFMigrationsHistory 中只有一条记录

原因是我们还没执行接口,导致EF core的自动迁移并没有生效

 

 

 

我们重新调用 store2 的接口,然后在看数据库表结构。发现 store2 中的Discount已经加上去了

 

 

 

 

 

总结

 EF core的自动迁移的具体实操步骤就是上文所述了。 

我再次重申,EF core的自动迁移并不是必备的,而是选配。 我非常不建议在运行多年并且有多租户结构的项目中使用 EF core 的 code first 模式。

不过假设你的项目已经分离得很不错,或是一个全新项目,我建议大家尝试。

 

关于代码

本系列的所有文章代码都会上传到github中,目前master是主分支,由于自动迁移部分只是附加内容,所以本文所有代码,请查看分支 EF_code_first_part3

 github 地址:

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

 

posted @ 2020-02-22 16:55  woailibian  阅读(2430)  评论(0编辑  收藏  举报