【问题标题】:Use multiple database in .net core在 .net core 中使用多个数据库
【发布时间】:2021-01-07 17:37:24
【问题描述】:

我想在我的应用程序中使用多个数据库,并且连接应该取决于调用 api 时的用户输入,我使用的是 .net core 3.1 和 postgresql。是否可以使用单个数据库上下文并在运行时更改连接字符串?

【问题讨论】:

    标签: postgresql .net-core ef-core-3.1


    【解决方案1】:

    ConnectionString 可以在 DbContext 的 OnConfiguring 方法中改变如下:

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        //get connectionString 
        var connString = _connectionStringService.GetConnectionString(); 
    
        optionsBuilder.UseSqlServer(connString);//or whatever 
    }
    

    此外,为了获取自定义连接字符串,您可以注入一些服务以在 OnConfiguring 方法中使用:

    public MyDbContext(IConnectionStringService connectionStringService) 
          : base(options)
    {
        _connectionStringService = connectionStringService) ;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-16
      • 1970-01-01
      • 2020-10-06
      • 2017-08-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多