Thursday, June 11, 2020

EF Core: Create Individual SQL Scripts for Each Migration

EF Classic/Core allows us to create a migration SQL script that can be used to execute to update a database. Sometimes it's really helpful to have individual migrations scripts for each of the migrations we have added rather than one large script.

This is a quick post on how we can create individual migrations for each migration we have added in EF Core using dotnet ef tool.

We can first get the list of migrations using the below command.
$migrations = dotnet ef migrations list `
    --no-build `
    --prefix-output | `
        where { $_.StartsWith("data") } | `
        foreach { $_.Substring($_.IndexOf(" ")).Trim() }
And this is going to output something like below.
List of Migrations
That's just exactly what we want. Here --preview-output and filtering are used to capture only what we need. Otherwise, we will get something like this.
Default Output
Since we have what we need, we can just iterate over this and create individual scripts, something like below.
$migrations = dotnet ef migrations list `
    --no-build `
    --prefix-output | `
        where { $_.StartsWith("data") } | `
        foreach { $_.Substring($_.IndexOf(" ")).Trim() }

$from = '0'
foreach ($migration in $migrations)
{
    dotnet ef migrations script $from $migration`
        --idempotent `
        --output "scripts/migrations/$migration.sql" `
        --no-build `
        --verbose

    $from = $migration
}
Here we are using from and to options, so this will generate a SQL script from the from migration to the specified to migration.

I hope this helps.

Happy Coding.
 
Regards,
Jaliya

No comments:

Post a Comment