Entity Framework Core demo for Seed data integrated into generated Migrations The goal of example project is to show the seeding data strategy in the scope of existed EF Core generated migration. The benefits of this approach:
- Separate seeding logic from scaffolded EF Core migrations
- Allow data seeding classes to use DI
- Incrementally run seeding
- Ensure that corresponding data seeding applied after migration
In the provided example seeding data functionality placed in the dedicated class and then injected to EF generated Migration
class
public partial class InitialMigration : Migration
{
private readonly IMigrationSeed _seed;
public InitialMigration(IMigrationSeed seed)
{
_seed = seed;
}
protected override void Up(MigrationBuilder migrationBuilder)
{
// Autogenerated migration code here...
_seed.UpSeed(migrationBuilder);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
// Autogenerated migration code here...
_seed.DownSeed(migrationBuilder);
}
}
Seeding functionality should be implemented in void UpSeed(MigrationBuilder migrationBuilder)
and counterpart void DownSeed(MigrationBuilder migrationBuilder)
methods.
For data manipulation you can use following MigrationBuilder
methods:
InsertData()
UpdateData()
DeleteData()
More info regarding the topic in the official documentation: Manual Migration Customization. If described above operations don't meet your needs, you can always use raw SQL queries by calling MigrationBuilder.Sql()
(Custom Migrations Operations).