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

Invoke-SqlCmd执行EF幂等迁移脚本失败:引用未创建列报错

问题:Azure DevOps发布管道执行EF幂等迁移脚本时的事务报错

我最近在把EF Core数据库迁移整合到Azure DevOps的发布管道里,目前的方案是这样的:

  • 构建阶段用dotnet ef migrations script --idempotent生成幂等迁移脚本,确保不管数据库当前状态如何都能安全执行
  • 发布阶段用Invoke-SqlCmd任务来运行这个脚本
  • 为了防止半迁移导致数据库处于损坏状态,我把整个脚本用事务包裹起来:开头加SET XACT_ABORT ON和BEGIN TRANSACTION,结尾加COMMIT

但执行的时候踩坑了——Invoke-SqlCmd报错说引用了不存在的列,比如我先在Foo表加Bar列,紧接着更新这个列的值,就会提示Invalid column name 'Bar'。明明脚本里是先加列再更新的,单独跑脚本没问题,一加上事务就炸了。

错误日志片段

Invoke-SqlCmd : Invalid column name 'Bar'.
At line:1 char:1

  • Invoke-SqlCmd -ServerInstance $server -Database $db -InputFile ...
  • + CategoryInfo          : InvalidOperation: (:) [Invoke-SqlCmd], SqlException
      + FullyQualifiedErrorId : SqlExceptionError,Microsoft.SqlServer.Management.PowerShell.GetScriptCommand
    

简化后的迁移脚本片段

IF NOT EXISTS(SELECT * FROM [__EFMigrationsHistory] WHERE [MigrationId] = N'20240520_AddFooBarColumn')
BEGIN
    ALTER TABLE [Foo] ADD [Bar] NVARCHAR(MAX) NULL;
END;
GO

IF NOT EXISTS(SELECT * FROM [__EFMigrationsHistory] WHERE [MigrationId] = N'20240520_UpdateFooBarColumn')
BEGIN
    UPDATE [Foo] SET [Bar] = 'DefaultValue' WHERE [Bar] IS NULL;
END;
GO

我用来生成带事务脚本的PowerShell代码

$migScriptPath = "$(Build.ArtifactStagingDirectory)\migrations.sql"
$transactionalScriptPath = "$(Build.ArtifactStagingDirectory)\migrations-with-transaction.sql"

# 写入事务头
@"
SET XACT_ABORT ON;
BEGIN TRANSACTION;
"@ | Out-File -FilePath $transactionalScriptPath -Encoding utf8

# 追加原迁移脚本
Get-Content -Path $migScriptPath | Out-File -FilePath $transactionalScriptPath -Encoding utf8 -Append

# 写入事务尾
"COMMIT TRANSACTION;" | Out-File -FilePath $transactionalScriptPath -Encoding utf8 -Append

有没有大佬遇到过这个问题?怎么解决这个报错?或者有没有更靠谱的Azure DevOps数据库部署流程方案?

内容的提问来源于stack exchange,提问作者Tomas Aschan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 08:38:17