Database Schema not changing at Runtime in Asp.net Core 2.2 & Entity Framework Core
我有一个应用程序,其中数据保存在不同用户的不同 sql 模式中。
例如
用户 1 数据保存在 SCHEMA1
用户 2 数据保存在 SCHEMA2
以前的应用程序是在 MVC 3 中开发的,它运行良好且符合预期。
现在我们正在迁移 .Net Core 2.2 中的应用程序,其中该功能不起作用
.net 核心没有
下面是 DBContext 文件
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 |
public class ApplicationDbContext : IdentityDbContext<ApplicationUser> { //public string Schema { get; set; } private readonly IConfiguration configuration; public string SchemaName { get; set; } public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) } public ApplicationDbContext(string schemaname) public DbSet<EmployeeDetail> EmployeeDetail { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) optionsBuilder.UseSqlServer(configuration["ConnectionStrings:SchemaDBConnection"]); var serviceProvider = new ServiceCollection().AddEntityFrameworkSqlServer() protected override void OnModelCreating(ModelBuilder modelBuilder) public string CacheKey } public class SchemaContextCustomize : ModelCustomizer } string schemaName = (dbContext as ApplicationDbContext).SchemaName; } |
我的问题是如何在运行时更改 schemaName
那么组织该机制的正确方法是什么:
通过用户凭据找出架构名称;
从特定模式的数据库中获取用户特定的数据。
我可以通过更改 onConfiguring 方法在运行时更改架构
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
public class ApplicationDbContext : IdentityDbContext<ApplicationUser> { public string SchemaName { get; set; } public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) } public ApplicationDbContext(string schemaname) public DbSet<EmployeeDetail> EmployeeDetail { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()) var serviceProvider = new ServiceCollection().AddEntityFrameworkSqlServer() protected override void OnModelCreating(ModelBuilder modelBuilder) modelBuilder.RemovePluralizingTableNameConvention(); public string CacheKey } string schemaName = (dbContext as ApplicationDbContext).SchemaName; } |
最好的方法是使用多租户架构能够为每个用户(租户)使用数据库模式
建议将此架构用于 Saas 应用程序
概念
Leta€?s 同意一些基本概念:
- 我们使用租户识别(或解决)策略来找出我们正在与哪个租户交谈
- 租户 DbContext 访问策略将找出检索(和存储)的方式
本文将向您展示如何使用 .net 核心实现多租户应用程序:https://stackify.com/writing-multitenant-asp-net-core-applications/
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/tech/269536.html