Generate SQL Script in Entity Framework Core

Here you will learn how to generate a SQL script from the EF Core model using migration which you can use to execute manually or add it in the source control.

In the previous Migrations chapter, we added the migration and created the "SchoolDB" database, as shown below.

EF Core Sample Project

It is recommended to deploy migrations to a production database is by generating SQL scripts.

The following table lists PMC/PowerShell commands and .NET Core CLI commands to generate a SQL script from the applied migrations.

PMC Commands .NET Core CLI commands Usage
Script-Migration dotnet ef migrations script Generates a SQL Script for all migrations
Script-Migration <FromMigrationName> dotnet ef migrations script <FromMigrationName> Generates a SQL script from the given migration to the latest migration.
Script-Migration <FromMigrationName> <ToMigrationName> dotnet ef migrations script <FromMigrationName> <ToMigrationName> Generates a SQL script from the specified from migration to the specified to migration.
Script-Migration -Idempotent dotnet ef migrations script --idempotent Generates idempotent scripts, which internally check which migrations have already been applied, and only apply missing ones.
Get-Migration dotnet ef migrations list List all existing migrations.

Execute the following migration command to generate a SQL script for entire database in PMC or PowerShell terminal.

Package Manager Console/PowerShell
generate-script

This will generate the SQL Script, as shown below.

If you use .NET Core CLI, then enter the following command.

.NET Core CLI
dotnet ef migrations script

You can also generate a SQL script from the specified migration till the last migration or from the specified from and to migrations. Refer commands in the above table.

Visit generating SQL script for more detail information.