【问题标题】:How to get SQL command generated by Generate function in EF-Core MigrationSqlGenerator?如何获取 EF-Core MigrationSqlGenerator 中 Generate 函数生成的 SQL 命令?
【发布时间】:2021-09-16 05:01:13
【问题描述】:

使用 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-core migration entity-framework-migrations


    【解决方案1】:

    MigrationSqlGenerator 生成一个MigrationCommand 实例列表,可以通过GetCommandList 方法从MigrationCommandListBuilder 获得。 SQL 命令文本包含在MigrationCommandCommandText 属性中。

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-05
      • 2019-10-31
      • 2017-12-16
      • 2022-01-06
      • 2023-02-03
      • 2021-10-24
      • 1970-01-01
      相关资源
      最近更新 更多