.net 在实体框架核心中配置多个Dbcontext(Oracle和SQL)
在我的项目中,我正在实体框架核心中处理两个数据库(SQL和Oracle)。我想根据appsettings.json中的配置值创建SQL和Oracle的上下文。SQL和Oracle DB表结构都是相同的 我想知道我是否有办法做到这一点。下面是我的示例代码.net 在实体框架核心中配置多个Dbcontext(Oracle和SQL),.net,.net-core,entity-framework-core,asp.net-core-webapi,.net,.net Core,Entity Framework Core,Asp.net Core Webapi,在我的项目中,我正在实体框架核心中处理两个数据库(SQL和Oracle)。我想根据appsettings.json中的配置值创建SQL和Oracle的上下文。SQL和Oracle DB表结构都是相同的 我想知道我是否有办法做到这一点。下面是我的示例代码 public class UserRepository: IUserRepository { private readonly SQLDBContext _context; private readonly OraDbContex
public class UserRepository: IUserRepository
{
private readonly SQLDBContext _context;
private readonly OraDbContext _contextOracle;
private readonly IConfiguration _config;
private readonly bool _dbSelect;
public UserRepository(SQLDBContext context, IConfiguration config, OraDbContext contextOracle, DbContext contexts)
{
_context = context;
_config = config;
_contextOracle = contextOracle;
_dbSelect = Convert.ToBoolean(config.GetSection("DbType").GetSection("SQLDbConfigured").Value);
}
}据我所知,当应用程序启动时,dbcontext被注册为startup.cs类中的服务 您的意思是要根据appsettings.json值注册dbcontext吗 如果这是您的要求,我建议您可以尝试在startup.cs ConfigureServices方法中添加以下代码:
//Check use which database
if (Convert.ToBoolean(Configuration.GetSection("DbType").GetSection("SQLDbConfigured").Value))
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
}
else
{
//code which used the Oracle
}
//检查使用哪个数据库
if(Convert.ToBoolean(Configuration.GetSection(“DbType”).GetSection(“sqldbconfigurated”).Value))
{
services.AddDbContext(选项=>
options.UseSqlServer(
GetConnectionString(“DefaultConnection”);
}
其他的
{
//使用Oracle的代码
}