postgresql - 在 .net core 中使用多个数据库
问题描述
我想在我的应用程序中使用多个数据库,并且连接应该取决于调用 api 时的用户输入,我使用的是 .net core 3.1 和 postgresql。是否可以使用单个数据库上下文并在运行时更改连接字符串?
解决方案
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) ;
}
推荐阅读
- c# - 部署后通过 API 上传文件不起作用
- python - 在 Docker 容器中对 Python PDB 使用交互模式
- java - 算法的时间复杂度取决于增量/减量步骤部分,而不是实际输入大小?
- python-3.x - 为聚合列提供别名并在 pyspark 中使用 groupBy 对结果进行四舍五入
- mysql - MYSQL - 比较来自两个不同表的行并返回两行之间的差异
- scala - 有什么更好的方法来制作一个对任何数字原语的列表求和的通用方法?
- jquery - jQuery Mask插件在同一元素上的电话号码的多个掩码不起作用
- youtube-dl - youtube-dl 没有下载最好的单文件版本
- python - Wavefile.read 给出文件格式 b'\x00\x00\x00\x1c'... 不明白
- mongodb - 更新所有文档 - 根据子集合中的订单设置子集合订单字段