ASP.NET核心EF代码第一个appsettings.json [英] ASP.NET Core EF Code First appsettings.json
问题描述
我有两个不同的连接字符串到MSSQL数据库。我想动态地将它传递给我的dbContext:
services.AddDbContext< ViggrContext>(options =>
options .UseSqlServer(Configuration.GetConnectionString( TestDatabase)));
我有两种类型的发布配置文件,一种用于测试,另一种用于生产环境。
在此配置文件中,我选择与数据库的连接。测试配置文件指向TestDatabase连接字符串,生产配置文件指向生产数据库。
但是,如何在代码的这一节中动态加载Startup.cs类? / p>
services.AddDbContext< ViggrContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString(TestDatabase ));
你有什么建议吗?
您可以在不同的appsettings文件中配置不同的环境连接字符串 -
对于测试环境,使用appsettings。 .json
数据:{
ViggrContext:{
ConnectionString :/ *<< == TestDatabase连接字符串* /
},
对于prod环境,使用appsettings。 prod .json
数据:{
ViggrContext:{
ConnectionString:/ *<< == ProdDatabase连接字符串* /
},
使用 ASPNETCORE_ENVIRONMENT 环境变量将当前环境设置为测试或 Prod 值。
在启动过程中,您可以像这样使用 -
服务。 AddDbC ontext< ViggrContext>(options =>
options.UseSqlServer(Configuration [Data:ViggrContext:ConnectionString]));
看看是否有帮助。
I'm looking for a method to switch dynamically between production and test environment.
I have two different connection strings to MSSQL databases. I want to dynamically pass this to my dbContext:
services.AddDbContext<ViggrContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("TestDatabase")));
I have two types of publish profiles, one for Test and another for Production environment. In this profile I choose a connection to the database. Ofcourse the Test profile points to the TestDatabase connection string and the Production profile points to the Production Database.
But how can I dynamically load the Startup.cs class in this section of the code?
services.AddDbContext<ViggrContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("TestDatabase")));
Do you have any suggestions ?
You can configure different environment connection strings in different appsettings files like this-
For test environment, use appsettings.test.json
"Data": {
"ViggrContext": {
"ConnectionString": "" /*<<== TestDatabase connection string */
},
For prod environment, use appsettings.prod.json
"Data": {
"ViggrContext": {
"ConnectionString": "" /*<<== ProdDatabase connection string */
},
Use ASPNETCORE_ENVIRONMENT environment variable to set current environment as Test or Prod values.
In Startup, you can use like this-
services.AddDbContext<ViggrContext>(options =>
options.UseSqlServer(Configuration["Data:ViggrContext:ConnectionString"]));
See if this helps.
这篇关于ASP.NET核心EF代码第一个appsettings.json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!