【问题标题】:Configuring Multiple Dbcontext(Oracle and SQL) in entity framework core在实体框架核心中配置多个 Dbcontext(Oracle 和 SQL)
【发布时间】:2021-01-22 06:06:39
【问题描述】:

在我的项目中,我在实体框架核心中处理两个数据库(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);
       
    }

}

【问题讨论】:

    标签: .net .net-core entity-framework-core asp.net-core-webapi


    【解决方案1】:

    据我所知,当应用程序启动时,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
            }
    

    【讨论】:

      猜你喜欢
      • 2018-07-22
      • 2017-10-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-08
      • 1970-01-01
      • 2020-05-16
      • 2020-10-15
      相关资源
      最近更新 更多