首页 > 解决方案 > 如何获取 EF-Core MigrationSqlGenerator 中 Generate 函数生成的 SQL 命令?

问题描述

使用 EF-Core 处理迁移时的自定义 SQL 命令。是否可以获取由覆盖Generate函数生成的 SQL 命令?

protected override void Generate(AddColumnOperation operation, IModel model, MigrationCommandListBuilder builder)
{
      base.Generate(operation, model, builder);
      var generatedSQL = ?; // <-- how can I get this SQL command?
}

标签: entity-framework-coremigrationentity-framework-migrations

解决方案


MigrationSqlGenerator生成MigrationCommand可以从MigrationCommandListBuilderviaGetCommandList方法获得的实例列表。SQL 命令文本包含CommandTextMigrationCommand.

因此,如果您确定基本调用会生成一个命令,那么您可以在之后从该列表中获取最后一个命令:

var generatedSQL = builder.GetCommandList().Last().CommandText;

没有任何假设的更通用的方法可能是这样的:

var commands = builder.GetCommandList();
var start = commands.Count;
base.Generate(operation, model, builder);
for (int i = start; i < commands.Count; i++)
{
    var generatedSQL = commands[i].CommandText;
}

推荐阅读