Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF Code First Migrations: recreate database and Seed

I'm using MigrateDatabaseToLatestVersion initializer and Seed method in DbMigrationConfiguration:

public sealed class Configuration : DbMigrationsConfiguration<Context>
{
    public Configuration()
    {
        AutomaticMigrationsEnabled = true;
        ContextKey = "...";
    }

    protected override void Seed(Context context)
    {
        context.MyEntities.AddOrUpdate(p => p.Name, new[]
        {
            new MyEntity { Name = "Name 1" },
        });
        context.SaveChanges();
    }
}

Automatic migration works fine with an existing database. But when there is no existing database (*.mdf, LocalDb), on first application start initializer only calls Up() methods from DbMigration without Seed. Seed method is called only after application restart.

If I manually call Upgrade-Database before first start it will create database and Seed method will be called on first run.

How to automatically initialize database with Seed data on application start when there is no existing database?

like image 893
dmitry.s Avatar asked Jan 01 '26 05:01

dmitry.s


1 Answers

I think this will really solve your problem:

Using Entity Framework Code First Migrations to auto-create and auto-update an application

In this code, after the database initialization, an instance of System.Data.Entity.Migrations.DbMigrator is used to manually apply all pending migrations.

The problem with this solution is that you need an initial migration. Although in the linked article it's not explained, I think that you can create an initial migration against an empty database by creating it from Nuget console before enabling automatic migrations.

like image 146
JotaBe Avatar answered Jan 02 '26 17:01

JotaBe