如何在 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.test.json
For test environment, use appsettings.test.json
"Data": {
"MyDbContext": {
"ConnectionString": "" /*<<== TestDatabase connection string */
},
对于 prod 环境,使用 appsettings.prod.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屋!