Entity Framework 使用 Visual Studio Team Services 发布的迁移

Entity Framework Migrations on release with Visual Studio Team Services

我正在尝试使用 Visual Studio Team Services 来构建/发布我的 MVC 应用程序到 Azure。

我一直在关注 tutorials here

目前我可以将我的更改推送到存储库,然后触发构建然后我可以手动 select 构建发布,使用发布定义中的设置自定义 web.config 文件和将站点推送到 Azure Web 应用程序上所需的位置。

现在,我的问题出在数据库上。直接从 Visual Studio 发布时,可以选择 运行 代码优先迁移。其中 creates/alters 表,然后是 运行 种子方法。如果您只是将站点部署到一个 Web 应用程序,这很好,但如果您将它多次部署到不同的实例,那么就不是了,因此想要使用 VS Team Services。

我看到发布定义中有 运行 bacpac 或 sql 文件的选项,但我想这需要为每个构建手动创建这些文件。

我确定我遗漏了什么。其他人如何在 builds/releases 中包含 model/database 更改。

如果有人能告诉我应该如何做就太好了,因为这方面似乎缺少 Microsoft 文档。

您应该能够通过添加以下代码来启用数据库迁移:

在您的 Startup.cs 文件中,在 Configuration 方法中,在开头添加以下行:

Database.SetInitializer(new MigrateDatabaseToLatestVersion<DefaultContext, Configuration>());

此外,在您的 Migrations/Configuration.cs 文件中,确保将以下行添加到您的配置方法中:

AutomaticMigrationsEnabled = true;
AutomaticMigrationDataLossAllowed = true; //either way works

使用这些选项让我在过去 运行 进行了数据库迁移。

根据您使用的 MVC 版本 运行 另一种选择是设置 web.config 值并手动 运行 以这种方式进行迁移。我有一个较旧的项目,我将这段代码放入应用程序开始的 Global.asax.cs 文件中:

        if (bool.Parse(ConfigurationManager.AppSettings["MigrateDatabaseToLatestVersion"]))
        {
            // Migrations to update the database.
            Database.SetInitializer<ApplicationDbContext>(null);
            var configuration = new Configuration();
            var migrator = new DbMigrator(configuration);

            migrator.Update();

            Log.Debug("Database migrations complete.");
        }