tetri
tetri

Reputation: 3584

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

Using EF-Core to handle custom SQL command over migration. Is it possible to get the SQL command generated by an overrided Generate function?

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

Upvotes: 1

Views: 202

Answers (1)

Ivan Stoev
Ivan Stoev

Reputation: 205759

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 property of the MigrationCommand.

So if you are sure that the base call generates a single command, then you could take the last command from that list afterwards:

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

A more generic approach without any assumptions could be like this:

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

Upvotes: 1

Related Questions