草庐IT

关于 c#:Database Schema 在 Asp.net Core 2.2 的运行时不变

codeneng 2023-03-28 原文

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 核心没有 IDbModelCacheKeyProvider 因为只有一个模式在工作

下面是 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)
        : base(options)
    {

    }

    public ApplicationDbContext(string schemaname)
        : base()
    {
        SchemaName = schemaname;
    }

    public DbSet<EmployeeDetail> EmployeeDetail { get; set; }



    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory())
                      .AddJsonFile("appsettings.json");
        var configuration = builder.Build();

        optionsBuilder.UseSqlServer(configuration["ConnectionStrings:SchemaDBConnection"]);

        var serviceProvider = new ServiceCollection().AddEntityFrameworkSqlServer()
                            .AddTransient<IModelCustomizer, SchemaContextCustomize>()
                            .BuildServiceProvider();
    }


    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.RemovePluralizingTableNameConvention();
        modelBuilder.HasDefaultSchema(SchemaName);
        base.OnModelCreating(modelBuilder);
    }

    public string CacheKey
    {
        get { return SchemaName; }
    }


}  


public class SchemaContextCustomize : ModelCustomizer
{
    public SchemaContextCustomize(ModelCustomizerDependencies dependencies)
        : base(dependencies)
    {

    }
    public override void Customize(ModelBuilder modelBuilder, DbContext dbContext)
    {
        base.Customize(modelBuilder, dbContext);

        string schemaName = (dbContext as ApplicationDbContext).SchemaName;
        (dbContext as ApplicationDbContext).SchemaName = schemaName;

    }
}

我的问题是如何在运行时更改 schemaName

那么组织该机制的正确方法是什么:

通过用户凭据找出架构名称;
从特定模式的数据库中获取用户特定的数据。

  • IDbModelCacheKeyProvider 与模式无关。您在 MVC 3 中使用的是一种解决方法,而不是使用具有相同上下文的不同模式的正确方法
  • @PanagiotisKanavos 感谢您提供信息,我已经设法使用自定义 UserManager 和以下上下文类解决了这个问题。如果可能的话,您能否分享示例或 URL 以实现具有相同上下文的不同模式,这将很有帮助


我可以通过更改 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)
        : base(options)
    {

    }

    public ApplicationDbContext(string schemaname)
        : base()
    {
        SchemaName = schemaname;
    }

    public DbSet<EmployeeDetail> EmployeeDetail { get; set; }



    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {

        var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory())
                      .AddJsonFile("appsettings.json");
        var configuration = builder.Build();

        var serviceProvider = new ServiceCollection().AddEntityFrameworkSqlServer()
                            .AddSingleton<IModelCustomizer, SchemaContextCustomize>()
                            .BuildServiceProvider();
        optionsBuilder.UseSqlServer(configuration["ConnectionStrings:SchemaDBConnection"]).UseInternalServiceProvider(serviceProvider);
    }


    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
       // modelBuilder.MapProduct(SchemaName);

        modelBuilder.RemovePluralizingTableNameConvention();
        if (!string.IsNullOrEmpty(SchemaName))
        {
            modelBuilder.HasDefaultSchema(SchemaName);
        }
        base.OnModelCreating(modelBuilder);
    }

    public string CacheKey
    {
        get { return SchemaName; }
    }
public class SchemaContextCustomize : ModelCustomizer
{
    public SchemaContextCustomize(ModelCustomizerDependencies dependencies)
        : base(dependencies)
    {

    }
    public override void Customize(ModelBuilder modelBuilder, DbContext dbContext)
    {
        base.Customize(modelBuilder, dbContext);

        string schemaName = (dbContext as ApplicationDbContext).SchemaName;
        (dbContext as ApplicationDbContext).SchemaName = schemaName;

    }
}
}

  • 你好。我知道这已经快一年了,但我不明白你实施的改变对你有什么帮助。我能看到的唯一(重要)区别是您将 SchemaContextCustomize 的时间跨度从 Transient 更改为 Singleton。甚至使用了 CacheKey 属性吗?您如何处理迁移(假设您使用它们)?


最好的方法是使用多租户架构能够为每个用户(租户)使用数据库模式
建议将此架构用于 Saas 应用程序

概念
Leta€?s 同意一些基本概念:

  • 我们使用租户识别(或解决)策略来找出我们正在与哪个租户交谈
  • 租户 DbContext 访问策略将找出检索(和存储)的方式

    本文将向您展示如何使用 .net 核心实现多租户应用程序:https://stackify.com/writing-multitenant-asp-net-core-applications/

  • 这与问题关系不大。 OP 询问如何更改上下文使用的架构,以连接到正确的租户架构
  • 在他的问题中,他说:"那么组织该机制的正确方法是什么:",我试图解释概念和哲学,而不是给他一些代码......
  • OP 已经使用具有多个模式的多租户架构。唯一有帮助的是一篇文章的链接,该文章解释了多种不同的技术,其中只有一种与多种模式相关。一个有用的答案将解释做什么和为什么,并包括相关的代码。

有关关于 c#:Database Schema 在 Asp.net Core 2.2 的运行时不变的更多相关文章

  1. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  2. ruby - 在 Ruby 程序执行时阻止 Windows 7 PC 进入休眠状态 - 2

    我需要在客户计算机上运行Ruby应用程序。通常需要几天才能完成(复制大备份文件)。问题是如果启用sleep,它会中断应用程序。否则,计算机将持续运行数周,直到我下次访问为止。有什么方法可以防止执行期间休眠并让Windows在执行后休眠吗?欢迎任何疯狂的想法;-) 最佳答案 Here建议使用SetThreadExecutionStateWinAPI函数,使应用程序能够通知系统它正在使用中,从而防止系统在应用程序运行时进入休眠状态或关闭显示。像这样的东西:require'Win32API'ES_AWAYMODE_REQUIRED=0x0

  3. ruby - 如何每月在 Heroku 运行一次 Scheduler 插件? - 2

    在选择我想要运行操作的频率时,唯一的选项是“每天”、“每小时”和“每10分钟”。谢谢!我想为我的Rails3.1应用程序运行调度程序。 最佳答案 这不是一个优雅的解决方案,但您可以安排它每天运行,并在实际开始工作之前检查日期是否为当月的第一天。 关于ruby-如何每月在Heroku运行一次Scheduler插件?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/8692687/

  4. ruby-on-rails - 如何在 ruby​​ 中使用两个参数异步运行 exe? - 2

    exe应该在我打开页面时运行。异步进程需要运行。有什么方法可以在ruby​​中使用两个参数异步运行exe吗?我已经尝试过ruby​​命令-system()、exec()但它正在等待过程完成。我需要用参数启动exe,无需等待进程完成是否有任何ruby​​gems会支持我的问题? 最佳答案 您可以使用Process.spawn和Process.wait2:pid=Process.spawn'your.exe','--option'#Later...pid,status=Process.wait2pid您的程序将作为解释器的子进程执行。除

  5. ruby - 无法运行 Rails 2.x 应用程序 - 2

    我尝试运行2.x应用程序。我使用rvm并为此应用程序设置其他版本的ruby​​:$rvmuseree-1.8.7-head我尝试运行服务器,然后出现很多错误:$script/serverNOTE:Gem.source_indexisdeprecated,useSpecification.Itwillberemovedonorafter2011-11-01.Gem.source_indexcalledfrom/Users/serg/rails_projects_terminal/work_proj/spohelp/config/../vendor/rails/railties/lib/r

  6. ruby - Sinatra:运行 rspec 测试时记录噪音 - 2

    Sinatra新手;我正在运行一些rspec测试,但在日志中收到了一堆不需要的噪音。如何消除日志中过多的噪音?我仔细检查了环境是否设置为:test,这意味着记录器级别应设置为WARN而不是DEBUG。spec_helper:require"./app"require"sinatra"require"rspec"require"rack/test"require"database_cleaner"require"factory_girl"set:environment,:testFactoryGirl.definition_file_paths=%w{./factories./test/

  7. ruby-on-rails - 无法让 rspec、spork 和调试器正常运行 - 2

    GivenIamadumbprogrammerandIamusingrspecandIamusingsporkandIwanttodebug...mmm...let'ssaaay,aspecforPhone.那么,我应该把“require'ruby-debug'”行放在哪里,以便在phone_spec.rb的特定点停止处理?(我所要求的只是一个大而粗的箭头,即使是一个有挑战性的程序员也能看到:-3)我已经尝试了很多位置,除非我没有正确测试它们,否则会发生一些奇怪的事情:在spec_helper.rb中的以下位置:require'rubygems'require'spork'

  8. c# - 如何在 ruby​​ 中调用 C# dll? - 2

    如何在ruby​​中调用C#dll? 最佳答案 我能想到几种可能性:为您的DLL编写(或找人编写)一个COM包装器,如果它还没有,则使用Ruby的WIN32OLE库来调用它;看看RubyCLR,其中一位作者是JohnLam,他继续在Microsoft从事IronRuby方面的工作。(估计不会再维护了,可能不支持.Net2.0以上的版本);正如其他地方已经提到的,看看使用IronRuby,如果这是您的技术选择。有一个主题是here.请注意,最后一篇文章实际上来自JohnLam(看起来像是2009年3月),他似乎很自在地断言RubyCL

  9. C# 到 Ruby sha1 base64 编码 - 2

    我正在尝试在Ruby中复制Convert.ToBase64String()行为。这是我的C#代码:varsha1=newSHA1CryptoServiceProvider();varpasswordBytes=Encoding.UTF8.GetBytes("password");varpasswordHash=sha1.ComputeHash(passwordBytes);returnConvert.ToBase64String(passwordHash);//returns"W6ph5Mm5Pz8GgiULbPgzG37mj9g="当我在Ruby中尝试同样的事情时,我得到了相同sha

  10. ruby-on-rails - before_filter 运行多个方法 - 2

    是否有可能:before_filter:authenticate_user!||:authenticate_admin! 最佳答案 before_filter:do_authenticationdefdo_authenticationauthenticate_user!||authenticate_admin!end 关于ruby-on-rails-before_filter运行多个方法,我们在StackOverflow上找到一个类似的问题: https://

随机推荐