当我有两个(或更多)具有不同数据库连接的配置文件时,如何通过迁移更新数据库?
How to update database via migrations when I have two (or more) config files with different database connections?
首先,没什么重要的,只是为了学习。
我有两个配置文件 appsettings.Development.json
和 appsettings.Staging.json
。
第一个有连接字符串:
"DatabaseConnection": "Data Source=BlaBla;Initial Catalog=MyDatabse-DEV;Integrated Security = True;"
第二个
"DatabaseConnection": "Data Source=BlaBla;Initial Catalog=MyDatabse-STG;Integrated Security = True;"
.
我想为暂存环境应用迁移(因此应该使用文件 appsettings.Staging.json
)。我已经声明了一个名为 ASPNETCORE_ENVIRONMENT
的环境变量,其值为“Staging”。
在Startup.cs
中我有以下代码:
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: false, reloadOnChange: true)
.AddEnvironmentVariables();
configuration = builder.Build();
无论我做什么,env.EnvironmentName
的值始终是“发展”。
解决方案
用“Staging”替换 env.EnvironmentName
变量 - 问题已解决!什么都没有燃烧。但是为了学习:有没有一种聪明的方法可以做到这一点。如果我错误地写了“Production”而不是“Staging”怎么办?
您可以使用以下命令在环境之间切换:
$Env:ASPNETCORE_ENVIRONMENT = "Local"
$env:ASPNETCORE_ENVIRONMENT = "Development"
$env:ASPNETCORE_ENVIRONMENT = "Release"
这些命令从 visual studio
进入您的 cli
然后使用以下命令,您可以在 select 正确的上下文中更新您的数据库。
Add-Migration -Context:ApplicationDbContext xxxxxx
Update-Database -Context:ApplicationDbContext
首先,没什么重要的,只是为了学习。
我有两个配置文件 appsettings.Development.json
和 appsettings.Staging.json
。
第一个有连接字符串:
"DatabaseConnection": "Data Source=BlaBla;Initial Catalog=MyDatabse-DEV;Integrated Security = True;"
第二个
"DatabaseConnection": "Data Source=BlaBla;Initial Catalog=MyDatabse-STG;Integrated Security = True;"
.
我想为暂存环境应用迁移(因此应该使用文件 appsettings.Staging.json
)。我已经声明了一个名为 ASPNETCORE_ENVIRONMENT
的环境变量,其值为“Staging”。
在Startup.cs
中我有以下代码:
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: false, reloadOnChange: true)
.AddEnvironmentVariables();
configuration = builder.Build();
无论我做什么,env.EnvironmentName
的值始终是“发展”。
解决方案
用“Staging”替换 env.EnvironmentName
变量 - 问题已解决!什么都没有燃烧。但是为了学习:有没有一种聪明的方法可以做到这一点。如果我错误地写了“Production”而不是“Staging”怎么办?
您可以使用以下命令在环境之间切换:
$Env:ASPNETCORE_ENVIRONMENT = "Local"
$env:ASPNETCORE_ENVIRONMENT = "Development"
$env:ASPNETCORE_ENVIRONMENT = "Release"
这些命令从 visual studio
进入您的 cli然后使用以下命令,您可以在 select 正确的上下文中更新您的数据库。
Add-Migration -Context:ApplicationDbContext xxxxxx
Update-Database -Context:ApplicationDbContext