首页 > 解决方案 > 如何:根据环境配置将提供者特定的 DbContext 选项添加到服务容器

问题描述

我想根据环境配置定位特定的 DbContext 提供程序。(即appsettings.sqlserver.dev.json、appsettings.oracle.dev.json、appsettings.sqlserver.prod.json、appsettings.oracle.prod.json等...)

下面的解决方案有效,但它似乎是一个 hack。此外,EF 似乎忽略了环境配置文件约定,因此您需要为 EF 命令维护默认的 appsettings.json。(添加迁移、删除迁移、更新数据库等...)

是否有任何提供程序环境设置可用于完成此操作?

启动.cs

public void ConfigureServices(IServiceCollection services)
{
    string dbProvider = Configuration["Database:Context:Provider"];            
    string dbConnectionString = Configuration["Database:Context:ConnectionString"];

    services.AddDbContext<DatabaseContext>(options =>
    {
        if (dbProvider == "SqlServer")
        {
            options.UseSqlServer(dbConnectionString, b => b.MigrationsAssembly("Eagle.Core.Web.Api"));
        }
        else if (dbProvider == "Oracle")
        {
            options.UseOracle(dbConnectionString, b => b.MigrationsAssembly("Eagle.Core.Web.Api"));
        }
            options.EnableSensitiveDataLogging(true);
    });            

    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}

标签: entity-framework-coredbcontext

解决方案


推荐阅读