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

时间:2016-11-28 23:06:29

标签: c# asp.net-core asp.net-core-1.0 appsettings

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

2 个答案:

答案 0 :(得分:13)

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

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

在startup.cs中访问:

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

答案 1 :(得分:0)

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

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