如何将代码优先迁移应用到 Azure 中的数据库?
How to apply code first migration to a database in Azure?
我正在开发我在 Azure 中托管的 ASP.NET 核心 API 应用程序。开发和部署都很顺利,但是当我需要应用迁移时,我遇到了问题。
开发时我使用本地 SQL 数据库,部署时我依赖 Azure SQL 数据库。我在开发中通过用户机密提供连接字符串,在生产中我使用 Azure Key Vault 来读取连接字符串。当然,还有一个 ASPNETCORE_ENVIRONMENT
环境变量,我在开发时将其保留为 Development
,并在部署到 Azure 后更改为 Production
。但是,问题是无论我的 ASPNETCORE_ENVIRONMENT
变量设置为 Development
还是 Production
,当我在开发时创建新的迁移并从 PowerShell 发出 dotnet ef update database
时,它只是更新我的本地数据库,而我的 Azure 数据库没有改变。有什么想法可以发布到 Azure 中的数据库的迁移吗?
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<MyContext>(
options => options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
}
public void Configure(
IApplicationBuilder app, IHostingEnvironment env, IServiceProvider serviceProvider)
{
if (env.IsProduction())
using (var context = serviceProvider.GetService<MyContext>())
context.Database.Migrate();
}
我正在开发我在 Azure 中托管的 ASP.NET 核心 API 应用程序。开发和部署都很顺利,但是当我需要应用迁移时,我遇到了问题。
开发时我使用本地 SQL 数据库,部署时我依赖 Azure SQL 数据库。我在开发中通过用户机密提供连接字符串,在生产中我使用 Azure Key Vault 来读取连接字符串。当然,还有一个 ASPNETCORE_ENVIRONMENT
环境变量,我在开发时将其保留为 Development
,并在部署到 Azure 后更改为 Production
。但是,问题是无论我的 ASPNETCORE_ENVIRONMENT
变量设置为 Development
还是 Production
,当我在开发时创建新的迁移并从 PowerShell 发出 dotnet ef update database
时,它只是更新我的本地数据库,而我的 Azure 数据库没有改变。有什么想法可以发布到 Azure 中的数据库的迁移吗?
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<MyContext>(
options => options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
}
public void Configure(
IApplicationBuilder app, IHostingEnvironment env, IServiceProvider serviceProvider)
{
if (env.IsProduction())
using (var context = serviceProvider.GetService<MyContext>())
context.Database.Migrate();
}