Database Migrations with Entity Framework

Created: Performing Database Migrations using .NET Core, SQL Server, and Entity Framework

Updated: 03 September 2023

Creating Migrations

When using Entity Framework database updates are defined by the application models available. In order to generate a migration script you would need to run the following command from your project directore

1
dotnet ef migrations add MIGRATION_NAME

This will create a new migration, you can also remove the last created migration with:

1
dotnet ef migrations remove

Database Updates

In order to update a database with the updated migration you can make use of the following command

1
dotnet ef database update

And in the case where a database cannot be accessed, you can generate the relevant SQL scripts using the following commands (documentation)

  1. Script all migrations
1
dotnet ef migrations script 0
  1. Script from initial state to Specific Migration
1
dotnet ef migrations script 0 MyTargetMigration
  1. Script from one migration to another
1
dotnet ef migrations script StartMigration EndMigration

When using the above scripts, the -i flag can be used to build a script that will work on a DB with any start-state, and the -o flag can be used to output to a file

1
dotnet ef migrations script 0 -i -o .\MyOutputFile.sql