asp.net - 使用 ASP.NET Core 和 EntityFramework 7 通过 Azure 中的迁移更改来更新生产数据库

标签 asp.net entity-framework azure asp.net-core asp.net-core-mvc

我有一个在本地运行的完整网络应用程序,我现在正在努力将其投入生产。该应用程序目前位于 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"]);
        });

这对于本地测试来说很好,但现在我已经准备好转向生产并有一些问题(找不到好的文档)。

  1. 如何使用 dnx 命令行将更改推送到生产数据库?一切都静态地绑定(bind)到应用程序定义的数据库,因此默认情况下它总是会转到我的本地数据库。

  2. 在 Azure 中配置数据库后,我是否只需在 Azure 上的 Web 应用程序设置中修改连接字符串,就像这样?

enter image description here

最佳答案

基础知识

您说过您有两个配置。一种用于本地,一种用于生产,每种都有一个连接字符串。在这种情况下,如果您的生产配置名为 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/

相关文章:

azure - 我的订阅已被删除,但仍显示在 Azure 门户中

azure - 为什么 IoT 中心消息在存储 JSON blob 中未正确解码?

c# - 尝试使用 Entity Framework 从数据库下载大文件时出错

java - Java 和 .NET 需要分布式缓存

c# - 多容器 Azure WebApp 无法与托管标识一起使用

asp.net-mvc-3 - Entity Framework 正在填充我的文本字段,尽管它们不是固定长度

entity-framework - Sqlite .NET 和 Entity Framework - "attempt to write a readonly database"

javascript - 有没有办法使用 JS 和 ASP

html - 最小化 ul 以戏剧性的方式改变 li

c# - 在我的控制台应用程序中调用 Entity Framework 类