Entity Framework Core data migration
Migration is a way to keep the database architecture in sync with the EF Core model by retaining data.
As shown in the figure above, the EF Core API builds an EF Core model from domain (entity) classes, and EF Core migration will create or update a database schema based on the EF Core model. Every time you change the domain class, you need to run a migration to keep the database schema up to date.
EF Core migration is a set of commands that you can execute in the NuGet package manager console or dotnet command line interface (CLI).
The following table lists the important migration commands in EF Core.
Package Manager console commands | dotnet command line command | Instructions |
---|---|---|
add-migration <migration name> | Add <migration name> | Create a migration by adding a migration snapshot |
Remove-migration | Remove | Delete the last migration snapshot |
Update-database | Update | Update the database schema based on the last migration snapshot |
Script-migration | Script | Generate SQL script using all migration snapshots |
Add migration
For the first time, you defined the initial domain class. At this point, your application does not have a database to store data in your domain class. Therefore, first, you need to create a migration.
Open the package manager console from Tools-> NuGet Package Manager-> Package Manager Console in Visual Studio, and then execute the following command to add the migration.
add-migration MyFirstMigration
If you are using the dotnet command line interface, please execute the following command.
dotnet ef migrations add MyFirstMigration
In the above command, MyFirstMigration is the name of the migration. This will create three files in the project's "Migration" folder as shown below.
- <timestamp> _ <migration name> .cs: main migration file, which contains the migration operations in the Up () and Down () methods The Up () method includes code for creating database objects, and the Down () method includes code for deleting database objects.
- <Timestamp> _ <migration name> .Designer.cs: migration metadata file, which contains information used by EF Core.
- <contextclassname> ModelSnapshot.cs: snapshot of the current model. This is used to determine the changes made when creating the next migration.
Now, after creating the migration snapshot, it is time to create the database.
Create or update a database
Use the following commands to create or update the database schema.
- Package Manager Console
Update-Database
- dotnet command line
dotnet ef database update
The Update command will create a database based on the context and domain class and migration snapshots, these snapshots are created using the add-migration or add command.
If this is the first migration, a table named __EFMigrationsHistory will also be created, which will store the names of all migrations and when they will be applied to the database.
Delete migration
If the last migration was not applied to the database, you can delete it. Use the following remove command to delete the last migration file created and restore the model snapshot.
- Package Manager Console
remove-migration
- dotnet command line
dotnet ef migrations remove
The above command will delete the last migration and restore the model snapshot to the previous migration. Please note that if the migration has been applied to the database, it will throw the following exception.
Migration <migration name> has been applied to the database. Restore it and try again. If the migration has been applied to other databases, consider using the new migration to revert its changes.
Restore migration
Suppose you change the domain class and use the add-migration command to create a second migration named MySecondMigration, and use the Update command to apply the migration to the database. However, for some reason, you want to restore the database to its previous state. In this case, use the update-database <migration name> command to restore the database to the specified previous migration snapshot.
- Package Manager Console
Update-database MyFirstMigration
- dotnet command line
dotnet ef database update MyFirstMigration
The above command will restore the database based on the migration named MyFirstMigration and delete all the changes applied to the second migration named MySecondMigration. This will also delete the MySecondMigration entry from the __EFMigrationsHistory table in the database.
Note: This will not delete the migration files related to MySecondMigration. Use the remove command to remove it from the project.
Generate SQL script
Use the following command to generate a SQL script for the database.
- Package Manager Console
script-migration
- dotnet command line
dotnet ef migrations script
The above script command will include all migrated scripts by default. You can use the -to and -from options to specify the migration scope.
From the package manager console command
You can use the package manager console in Visual Studio to execute the migration commands in Entity Framework Core. Open the package manager console from Tools-> NuGet Package Manager-> Package Manager Console in Visual Studio to execute the following commands.
Package Manager Console | usage |
---|---|
Get-Help entityframework | Get help entityframework to display information about Entity Framework commands |
Add-Migration | <Migration name> Create migration by adding migration snapshot |
Remove-Migration | Delete the last migration snapshot |
Update-Database | Update the database schema based on the last migration snapshot |
Script-Migration | Generate SQL script using all migration snapshots |
Scaffold-DbContext | Generate DbContext and entity type classes for the specified database. This is called reverse engineering |
Get-DbContext | Get information about DbContext type |
Drop-Database | Delete the database |
Get-Help
get-help entityframework
Add-Migration Add migration
get-help entityframework
Remove-Migration
get-help entityframework
Update-Database
get-help entityframework
Script-migration script migration
get-help entityframework
scaffold-dbcontext scaffold database context
get-help entityframework
Get-DbContext
get-help entityframework
Drop-Database
get-help entityframework
Command line interface commands for migration
Use .NET Core Command List Interface to execute Entity Framework core commands. To use the .NET CLI, add the <DotNetCliToolReference Include = "Microsoft.EntityFrameworkCore.Tools.DotNet" Version = "2.0.0" /> under the <ItemGroup> node by editing the .csproj file of the .NET Core project.
Open a command prompt, then navigate to the root folder of the project, and enter dotnet ef --help to list the EF Core commands, as shown below.
[External chain image transfer failed, the source site may have an anti-theft chain mechanism, it is recommended to save the image and upload it directly (img-cD0PztSl-1581165405066) (d: \ note \ efcore \ pic \ 31.png)]
As you can see above, there are three main EF commands available: database, dbcontext and migration. The following table lists all EF commands and subcommands.
command | Subcommand | usage |
---|---|---|
Database | drop | Delete the database |
update | Update the database to the specified migration | |
DbContext | info | Get information about DbContext type |
list | List available DbContext types | |
scaffold | Provide DbContext and entity type for database | |
Migration | add | Add new migration |
list | List available migrations | |
remove | Delete the last migration | |
script: | Generate SQL script from migration |
Let's look at the available options for each command.
Database Drop
dotnet ef database drop
Database Update
dotnet ef database update
DbContext Info
dotnet ef dbcontext info
DbContext List
dotnet ef dbcontext list
DbContext Scaffold
dotnet ef dbcontext scaffold
Add
dotnet ef migrations add
List
dotnet ef migrations list
Remove
dotnet ef migrations remove
Script
dotnet ef migrations script