Wednesday, April 13, 2022

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

Issue

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

Solution

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


Answered By - Ivan Stoev
Answer Checked By - Robin (PHPFixing Admin)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.