【问题标题】:How to apply database code first migrations in an azure deployed application?如何在 Azure 部署的应用程序中应用数据库代码优先迁移?
【发布时间】:2018-10-19 00:12:16
【问题描述】:

我刚刚将应用程序部署到 Azure 应用服务中。 我的项目确实有要应用的迁移。 但我无法使用 azure app 命令行应用它们

dotnet ef 数据库更新

D:\home\site\wwwroot> 找不到匹配命令“dotnet-ef”的可执行文件

如何远程应用它们?

【问题讨论】:

    标签: .net azure ef-code-first dotnet-cli


    【解决方案1】:

    您可以在 appsettings.json 中设置 Azure 连接字符串而不是本地连接字符串并执行迁移或dotnet ef database update

    【讨论】:

      【解决方案2】:

      我有一个非常相似的问题。我正在开发一个 .NET Core 3.0 Web 应用程序(带有个人用户帐户的 Visual Studio Angular 模板)。我正在使用 AzureDevops 构建项目并将其发布到 Azure 上的应用服务。

      首先,你可以使用

      dotnet tool install --global dotnet-ef --version {version compatible with your project}
      

      在您的管道中,在构建过程中为 dotnet 安装 ef 扩展。

      我假设您想要更新远程/生产数据库。要以安全的方式执行此操作,您可以将具有特定凭据和连接字符串的 appsettings.json 文件上传到 Azure Azure DevOps 管道中的安全文件。见下图。

      appsettings.json in Secure files

      然后您可以通过 Download Secure File task 在构建管道中引用该文件(该文件将该文件下载到构建的工作目录中)并使用 dotnet ef 数据库更新像这样:

      migration script

      注意在上面的迁移脚本中:

      • app 是我的项目名称,
      • 我将文件重命名为 appsettings.json,因为我已将其上传到 Secure files,但名称不同,
      • 您不需要使用 lscat 命令 - 它们用于调试目的
      • 命令 dotnet ef database update 使用您已上传到 Secure Files 的生产 appsettings.json。

      【讨论】:

        【解决方案3】:

        对于dotnet-ef,我假设您在谈论 Entity Framework Core。我尝试在 KUDU 的 D:\home\site\wwwroot 和 VS 的 Package Manager Console 下运行 dotnet ef database update,我可能会遇到与您提到的相同的问题。

        我发现了一个类似的问题No executable found matching command "dotnet-ef":

        DotNet CLI 只能在项目目录中解析“dotnet-ef”。

        我可以通过 Powershell 运行命令dotnet ef migrations adddotnet ef database update。具体命令用法可以关注EF Core .NET Command-line Tools

        如何在 Azure 部署的应用程序中应用数据库代码优先迁移?

        根据我的理解,你不能这样做。您可能需要手动运行 update-database,因为 vivek nuna 在 VS 的包管理器控制台下回答,或者您可以使用 Powershell 和 cd 到您的项目目录,并执行 dotnet ef database update 将您的上下文的任何未决迁移应用到数据库,然后将您的应用程序部署到 Azure Web 应用程序。

        另外,EF 不支持自动迁移,您可能需要手动执行Add-Migrationdotnet ef migrations add 来添加迁移文件。您可以显式执行命令以应用迁移,也可以在代码中应用迁移。您可以在Startup.cs文件的Configure方法中添加以下代码:

        using (var scope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
        {
            scope.ServiceProvider.GetRequiredService<ApplicationDbContext>().Database.Migrate();
        }
        

        另外,你也可以关注这个类似的issue

        【讨论】:

          【解决方案4】:

          在 Azure 上运行迁移的最佳方法之一是在 Visual Studio 中运行 update-database 命令。但是这个命令不会运行。您的客户端 IP 地址应该可以访问 Azure。

          您可以关注RUN MIGRATIONS ON THE AZURE。 Asp.Net Zero 构建在 Asp.Net Core 之上,因此这些步骤对您有用。

          【讨论】:

          猜你喜欢
          • 2019-03-16
          • 2018-07-02
          • 2013-04-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-05-29
          相关资源
          最近更新 更多