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

Using connection string from appsettings.json to startup.cs

目前在启动中,我的 sql 服务器字符串如下所示:

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

此外,如果我有不同的数据库用于测试和质量检查,我如何让 ASP.NET 应用知道为每个环境使用一个连接?

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

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();
}

对连接字符串使用正确的结构:

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

访问startup.cs:

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

首先为 SQL 服务器“Microsoft.EntityFrameworkCore.SqlServer”添加包,然后添加

services.AddDbContext(选项=> options.UseSqlServer(Configuration.GetConnectionString("默认连接")));