Add Migration
The common solution is using C#
itself as the language of migration script. So we'll need
- A package that provides the migration features
- A cli tool to auto generate source files represents the migration.
Add dependency
sh
dotnet add package Microsoft.EntityFrameworkCore.Tools
1
sh
dotnet tool install -g dotnet-ef
1
Add a migration
How migration organized
The following will generate a class with two parts inside your project as Migrations/<timestamp>_<class_name>.cs
and Migration/<timestamp>_<class_name>.Designer.cs
.
sh
dotnet-ef migrations add <class_name>
1
Migration.Up
will be invoked when upgrading to this version of migration.Migration.Down
will be invoked when reverting to previous migration.
cs
using Microsoft.EntityFrameworkCore.Migrations;
/// <inheritdoc />
public partial class <class_name> : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder) { /* ... */ }
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder) { /* ... */ }
}
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
Another part of your migration takes the job of modeling, it stores the status of the schema when generating this migration.
cs
[DbContext(typeof(MoviesContext))]
[Migration("<timestamp>_<class_name>")]
partial class <class_name>
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder) { /* ... */ }
}
1
2
3
4
5
6
7
2
3
4
5
6
7
How snapshot organized
Adding migration also generates or updates snapshot of the current schema, it represents the current status so that migrations can have it as a reference to do reversion or upgrade
INFO
- A migration was only generated once.
- Snapshot updates on every migration.
WARNING
You should never manually edit snapshot or migrations except altering columns