如何在ASP.net Core中基于环境添加DbContext [英] How to add DbContext based on environment in ASP.net Core
问题描述
这是我当前在Startup.cs的ConfigureServices方法中添加DbContext的方式:
This is how I am currently adding my DbContext in my ConfigureServices method in Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
.....
services.AddDbContext<MyDbContext>(options =>
options.UseMySQL(Configuration.GetConnectionString("DefaultConnection")));
.....
}
我的连接字符串存储在我的appsettings.json文件中,例如:
And my connection string is stored in my appsettings.json file, like this for example:
{
....
"ConnectionStrings": {
"DefaultConnection": "server=localhost;user id=root;password=root;database=mydb;sslmode=none"
}
....
}
如果我想切换要连接的数据库,如果是开发与生产环境,如何使 services.AddDbContext()切换数据库?
If I want to switch which database is being connected, how do I make the "services.AddDbContext()" switch the database if it is "Development" vs. "Production" environments?
推荐答案
您可以在像这样的不同 appsettings
文件中配置不同的环境连接字符串-
You can configure different environment connection strings in different appsettings
files like this-
对于测试环境,请使用appsettings。测试 .json
For test environment, use appsettings.test.json
"Data": {
"MyDbContext": {
"ConnectionString": "" /*<<== TestDatabase connection string */
},
对于产品环境,请使用appsettings。产品 .json
For prod environment, use appsettings.prod.json
"Data": {
"MyContext": {
"ConnectionString": "" /*<<== ProdDatabase connection string */
},
使用 ASPNETCORE_ENVIRONMENT
环境变量将当前环境设置为Test或Prod值。
Use ASPNETCORE_ENVIRONMENT
environment variable to set current environment as Test or Prod values.
在启动中,您可以像这样-
In Startup, you can use like this-
services.AddDbContext<MyContext>(options =>
options.UseSqlServer(Configuration["Data:MyContext:ConnectionString"]));
这篇关于如何在ASP.net Core中基于环境添加DbContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!