我们从 .NET 6 升级到了 .NET 8,现在该dotnet-ef
工具会在中间生成换行符,这很sqlcmd
让人不爽。这是一个兼容级别为 150 的 Azure SQL 数据库。
dotnet ef migrations script --project hidden --startup-project hidden
--output AppDbContext.sql --context AppDbContext --verbose --idempotent
sqlcmd -S "hidden" -d "hidden" -U "hidden" -P "hidden" -i "D:\AppDbContext.sql"
消息 102,级别 15,状态 1,服务器隐藏,第 11 行
“;”附近语法不正确
我手动运行了 SQL,但似乎它不是空的BEGIN...END
:
IF NOT EXISTS (
SELECT * FROM [Historical].[EFMigration]
WHERE [MigrationId] = N'20210814000018_AddSPHedgeReport'
)
BEGIN
END;
GO
EF 6 没有用于生成这个。
using Microsoft.EntityFrameworkCore.Migrations;
namespace hidden
{
public partial class AddSPHedgeReport : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string?>(
name: "FixedProperty",
schema: "Reports",
table: "SectionColumn",
nullable: true);
migrationBuilder.RunScripts("20210813");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "FixedProperty",
schema: "Reports",
table: "SectionColumn");
}
}
}
另一个失败的例子:
#nullable disable
using Microsoft.EntityFrameworkCore.Migrations;
namespace hidden
{
public partial class AuditTables : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.RunScripts("20220920");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
}
}
}
以下是具体ScriptHelper
操作:
public static class ScriptHelper
{
public static void RunScripts(this MigrationBuilder migrationBuilder, string version)
{
var assembly = Assembly.GetExecutingAssembly();
var resourceNames = assembly.GetManifestResourceNames().Where(str => str.EndsWith(version + ".sql"));
foreach (var resourceName in resourceNames)
{
using (var stream = assembly.GetManifestResourceStream(resourceName))
using (var reader = new StreamReader(stream))
{
var sql = reader.ReadToEnd();
migrationBuilder.Sql(sql);
}
}
}
}
使用该
Trim()
方法可以有效地删除 SQL 脚本中的前导和尾随空格,增强其兼容性并防止执行期间出现与格式相关的错误。