Skip to content

Entity Framework Core demo for Seed data integrated into generated Migrations

License

Notifications You must be signed in to change notification settings

nazimkov/EFCoreSeedMigrations

Repository files navigation

Build status

EFCoreSeedMigrations

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:

  1. Separate seeding logic from scaffolded EF Core migrations
  2. Allow data seeding classes to use DI
  3. Incrementally run seeding
  4. 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).

About

Entity Framework Core demo for Seed data integrated into generated Migrations

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages