问题 使用从appsettings.json到startup.cs的连接字符串


目前在Startup中,我的sql server字符串如下所示:

public void ConfigureServices(IServiceCollection services)
{
    var connection = @"Server=servername;Database=database;Trusted_Connection=True;MultipleActiveResultSets=true";
    services.AddDbContext<CRAMSContext>(options => options.UseSqlServer(connection));
}

我如何使用appsettings.json中的内容:

{
  "Data": {
    "DefaultConnection": {
    "ConnectionString": "Data Source=server;Initial Catalog=database;Trusted_Connection=True;MultipleActiveResultSets=true"
  },
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Debug",
      "System": "Information",
      "Microsoft": "Information"
    }
  }
}

在新的ASP.NET 1.0 CORE新设置中看起来像这样看起来像这样参数化:

public void ConfigureServices(IServiceCollection services)
{
    var connection2 = new SqlConnection connectionString;
    services.AddDbContext<CRAMSContext>(options => options.UseSqlServer(connection2));
}

另外,如果我有一个不同的测试数据库和qa,我如何知道ASP.NET应用程序为每个环境使用连接?

我的启动类已经在根目录中定义如下:

public Startup(IHostingEnvironment env)
{
    var builder = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
        .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
        .AddEnvironmentVariables();
    Configuration = builder.Build();
}

12134
2017-11-28 23:06


起源



答案:


使用适当的连接字符串结构:

{
  "ConnectionStrings": {
    "DefaultConnection": "xxx"
  }
}

在startup.cs中访问:

services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

11
2018-04-06 23:28



我明白了: Error: The name "Configuration" does not exist in the current context。我错过了哪个套餐?编辑:没关系,这是v2预发行版中的一个问题。在1.1稳定版中,没关系。 - JedatKinports
你错过了 IConfiguartionRoot Startup.cs文件中的方法。将其命名为configuaration,添加一个get,它就完成了。 - dev.mi


答案:


使用适当的连接字符串结构:

{
  "ConnectionStrings": {
    "DefaultConnection": "xxx"
  }
}

在startup.cs中访问:

services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

11
2018-04-06 23:28



我明白了: Error: The name "Configuration" does not exist in the current context。我错过了哪个套餐?编辑:没关系,这是v2预发行版中的一个问题。在1.1稳定版中,没关系。 - JedatKinports
你错过了 IConfiguartionRoot Startup.cs文件中的方法。将其命名为configuaration,添加一个get,它就完成了。 - dev.mi