如何获取 EF-Core MigrationSqlGenerator 中生成函数生成的 SQL 命令?

How to get SQL command generated by Generate function in EF-Core MigrationSqlGenerator?

使用 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?
}

MigrationSqlGenerator produces a list of MigrationCommand instances which can be obtained from the MigrationCommandListBuilder via GetCommandList method. The SQL command text is contained in the CommandText 属性 的 MigrationCommand.

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

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;
}