Generate SQL script from Entity Framework migration script

It is not recommended to execute Entity Framework migration scripts in production, It is important that you execute all SQL steps manually on the production database section-by-section to immediately see the result and be able to recover in case a destructive action goes wrong.

The Visual Studio .NET application templates contain Entity Framework migration scripts to set up your local database to match the sample code. To generate the SQL script you can execute by hand on the production database

Install the EF Core .NET Command-line Tools

  1. Open a command window in the folder of the project that contains the database access code
  2. In the command line execute
    dotnet add package Microsoft.EntityFrameworkCore.Design
    dotnet restore
  3. Test the dotnet ef installation with
    dotnet ef

 

Script the .NET Entity Framework migrations

  1. Open a command window in the folder of the project that contains the database access code
  2. In the command line execute
    1. To generate the SQL script to bring the current development database to the scripted configuration state, use the –idempotent option.
      (Generating idempotent scripts for migration is not currently supported by MySql)

      dotnet ef migrations script --idempotent --output "script.sql" --context MY_DBCONTEXT
    2. To generate the SQL script based on the entire migration script to update the production database to match the template after you have updated the development database
      dotnet ef migrations script --output "script.sql" --context MY_DBCONTEXT

 

 

Leave a Reply