2016-11-28 55 views
9

目前,我有我的SQL服務器字符串看起來像這樣:使用連接字符串從appsettings.json在啓動到startup.cs

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新設置把目光paramertized這樣的:

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

回答

10

使用的連接字符串結構合理:

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

在startup.cs訪問:

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

我get:'錯誤:名稱「配置」在當前上下文中不存在。我錯過了哪個包?編輯:沒關係,這是v2的預發行版中的問題。在1.1穩定版本中沒關係。 – JedatKinports

+1

您在Startup.cs文件中缺少'IConfiguartionRoot'方法。將其命名爲configuaration,添加一個get,然後完成。 –