2016-11-28 13 views
9

Hiện nay trong Startup, tôi có chuỗi sql máy chủ của tôi nhìn như thế này:Sử dụng chuỗi kết nối từ 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)); 
} 

Làm thế nào để sử dụng những gì trong appsettings.json tôi:

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

để trông giống như thế này trong ASP.NET 1.0 CORE thiết lập mới mới để nhìn paramertized như thế này:

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

Al vì vậy, nếu tôi có một cơ sở dữ liệu khác nhau cho thử nghiệm và qa, làm cách nào để ứng dụng ASP.NET biết sử dụng kết nối cho mỗi môi trường?

lớp khởi động của tôi đã được xác định ở thư mục gốc như thế này:

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

Trả lời

10

Sử dụng cấu trúc phù hợp cho các chuỗi kết nối:

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

Access trong startup.cs:

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

tôi get: 'Lỗi: Tên" Cấu hình "không tồn tại trong ngữ cảnh hiện tại'. Tôi thiếu gói nào? EDIT: Không sao, đây là vấn đề trong bản phát hành trước của v2. Trong phiên bản ổn định 1.1 nó là ok. – JedatKinports

+1

bạn đang thiếu phương thức 'IConfiguartionRoot' trong tệp Startup.cs. Đặt tên cho nó là configuaration, thêm một get vào nó, và bạn đã hoàn tất. –

Các vấn đề liên quan