我有一个在本地运行的完整网络应用程序,我现在正在努力将其投入生产。该应用程序目前位于 Azure 上,并监视 git 存储库以了解新的部署,效果非常好。
但是,应用程序在其 appsettings.json
中有一个用于连接字符串的连接,如下所示:
"database": {
"connection": "Data Source=(localdb)\\mssqllocaldb;Initial Catalog=Foo"
},
// In Startup()
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddEnvironmentVariables();
// In ConfigureServices(...)
services.AddEntityFramework()
.AddSqlServer()
.AddDbContext<FooDbContext>(options =>
{
options.UseSqlServer(Configuration["database:connection"]);
});
这对于本地测试来说很好,但现在我已经准备好转向生产并有一些问题(找不到好的文档)。
如何使用
dnx
命令行将更改推送到生产数据库?一切都静态地绑定(bind)到应用程序定义的数据库,因此默认情况下它总是会转到我的本地数据库。在 Azure 中配置数据库后,我是否只需在 Azure 上的 Web 应用程序设置中修改连接字符串,就像这样?
最佳答案
基础知识
您说过您有两个配置。一种用于本地,一种用于生产,每种都有一个连接字符串。在这种情况下,如果您的生产配置名为 appsettings.development.json
,您可以执行以下操作:
启动()
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
配置服务(...)
services.AddEntityFramework()
.AddSqlServer()
.AddDbContext<FooDbContext>(options =>
{
options.UseSqlServer(Configuration["database:connection"]);
});
appsettings.生产.json
{
"database": {
"connection": "Server=tcp:yr3d5dswl.database.windows.net,1433;Database=EFMigrationDemo;User ID=mvp2015@yr3d5dswl;Password=3f4g%^BD45bcE;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;"
}
}
命令行
dotnet ef database update -e Production
这将更新您的生产数据库。
高级
与您的持续集成相集成。通过将 postbuild
脚本添加到您的project.json,让迁移在构建时更新实时数据库。 Azure 将在每个部署上运行它。
"scripts": {
"postbuild": [ "dotnet ef database update" ]
}
如果您想使用环境变量而不是 appsettings.production.json
文件,请查看 Setting the SQL connection string for ASP.NET 5 web app in Azure 。这将使您的用户名/密码远离您的 git 存储库。
引用文献
关于asp.net - 使用 ASP.NET Core 和 EntityFramework 7 通过 Azure 中的迁移更改来更新生产数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36453814/