You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过YML文件在Heroku Postgres中执行SQL迁移脚本?

GitHub Actions自动执行Heroku Postgres EF Core迁移方案

前置要求

  • Heroku应用已绑定Heroku Postgres插件,系统自动生成DATABASE_URL环境变量
  • GitHub仓库Secrets中配置两个变量:
    • HEROKU_API_KEY:Heroku账户API密钥(在Heroku账户设置里生成)
    • HEROKU_APP_NAME:你的Heroku应用名称

完整GitHub Actions YML配置

在仓库.github/workflows/下创建heroku-deploy-migrations.yml,内容如下:

name: Deploy to Heroku & Apply Migrations

on:
  push:
    branches: [ main ] # 按需修改触发分支
  pull_request:
    branches: [ main ]

jobs:
  deploy-and-migrate:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Setup .NET 6 SDK
        uses: actions/setup-dotnet@v4
        with:
          dotnet-version: '6.x'

      - name: Restore NuGet dependencies
        run: dotnet restore

      - name: Build release version
        run: dotnet build --configuration Release --no-restore

      - name: Login to Heroku
        uses: akhileshns/heroku-deploy@v3.12.12
        with:
          heroku_api_key: ${{ secrets.HEROKU_API_KEY }}
          heroku_app_name: ${{ secrets.HEROKU_APP_NAME }}
          heroku_email: your-heroku-email@example.com # 替换为你的Heroku注册邮箱
          justlogin: true

      - name: Execute EF Core migrations
        env:
          DATABASE_URL: ${{ steps.heroku-deploy.outputs.DATABASE_URL }}
        run: dotnet ef database update --configuration Release --connection "$DATABASE_URL"
        working-directory: ./YourDbContextProject # 替换为包含DbContext的项目路径

核心细节说明

  • 连接字符串兼容:EF Core 6+原生支持Heroku的postgres://user:pass@host:port/db格式连接字符串,无需手动转换;若用低于6的版本,可加一段sed命令转换:
    CONN_STR=$(echo "$DATABASE_URL" | sed -e 's/postgres:///Host=/;s/:@/;Username=/;s/:/;Port=/;s/\//;Database=/')
    dotnet ef database update --configuration Release --connection "$CONN_STR"
    
  • 迁移执行逻辑:dotnet ef database update会自动对比数据库当前状态和本地迁移文件,执行所有未应用的迁移,无需提前生成SQL脚本。
  • Heroku登录:借助akhileshns/heroku-deploy action完成认证,同时自动获取应用的DATABASE_URL,省去手动配置的麻烦。

备选方案:通过Heroku远程命令执行迁移

如果不想在GitHub Actions环境中执行迁移,也可以部署后在Heroku dyno中运行命令:
在YML的部署步骤后添加:

- name: Run migrations on Heroku dyno
  run: heroku run dotnet ef database update --configuration Release -a ${{ secrets.HEROKU_APP_NAME }}
  env:
    HEROKU_API_KEY: ${{ secrets.HEROKU_API_KEY }}

这种方式依赖Heroku的运行环境,无需在GitHub Actions中处理.NET环境细节,但需要确保应用已成功部署。

内容的提问来源于stack exchange,提问作者Mateus Kern

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 21:36:21