在实体框架核心中配置多个DbcontextOracle和SQL

问题描述

在我的项目中,我正在处理实体框架核心中的两个数据库sql和Oracle)。我想基于appsettings.json中的配置值创建sql和Oracle的上下文。 sql和Oracle DB表结构都相同。

我想知道是否有任何方法可以实现这一目标。下面是我的示例代码

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
        }