C# ASP.NET核心EF代码第一个appsettings.json

C# ASP.NET核心EF代码第一个appsettings.json,c#,asp.net,entity-framework,asp.net-core,entity-framework-core,C#,Asp.net,Entity Framework,Asp.net Core,Entity Framework Core,我正在寻找一种在生产环境和测试环境之间动态切换的方法 我有两个不同的MSSQL数据库连接字符串。我想动态地将其传递到我的dbContext: services.AddDbContext<ViggrContext>(options => options.UseSqlServer(Configuration.GetConnectionString("TestDatabase"))); services.AddDbContext(选项=

我正在寻找一种在生产环境和测试环境之间动态切换的方法

我有两个不同的MSSQL数据库连接字符串。我想动态地将其传递到我的dbContext:

   services.AddDbContext<ViggrContext>(options =>
                    options.UseSqlServer(Configuration.GetConnectionString("TestDatabase")));
services.AddDbContext(选项=>
options.UseSqlServer(Configuration.GetConnectionString(“TestDatabase”));
我有两种类型的发布配置文件,一种用于测试,另一种用于生产环境。 在此配置文件中,我选择了与数据库的连接。当然,测试配置文件指向TestDatabase连接字符串,生产配置文件指向生产数据库。

但是如何在代码的这一部分中动态加载Startup.cs类呢

   services.AddDbContext<ViggrContext>(options =>
                    options.UseSqlServer(Configuration.GetConnectionString("TestDatabase")));
services.AddDbContext(选项=>
options.UseSqlServer(Configuration.GetConnectionString(“TestDatabase”));

您有什么建议吗?

您可以像这样在不同的appsettings文件中配置不同的环境连接字符串-

     services.AddDbContext<ViggrContext>(options =>
options.UseSqlServer(Configuration["Data:ViggrContext:ConnectionString"]));
对于测试环境,请使用appsettings。test.json

 "Data": {
    "ViggrContext": {
      "ConnectionString": "" /*<<== TestDatabase connection string */
    },
“数据”:{
“背景”:{
“连接字符串”:”/*
     services.AddDbContext<ViggrContext>(options =>
options.UseSqlServer(Configuration["Data:ViggrContext:ConnectionString"]));