首页 > 解决方案 > 在 .net core 中使用多个数据库

问题描述

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

标签: postgresql.net-coreef-core-3.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) ;
}

推荐阅读