如何:根据环境配置将提供程序特定的DbContext选项添加到服务容器

时间:2019-06-13 14:15:01

标签: entity-framework-core dbcontext

我想基于环境配置来定位特定的DbContext提供程序。 (即appsettings.sqlserver.dev.json,appsettings.oracle.dev.json,appsettings.sqlserver.prod.json,appsettings.oracle.prod.json等...)

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

有没有可用于完成此操作的提供程序环境设置?

Startup.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);
}

0 个答案:

没有答案
相关问题