Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework Migrations - Seed runs even if no migration?

I have set up a simple Migration with AutomaticMigrationsEnabled = false. Everything works great from visual studio or when using MigrateDatabaseToLatestVersion.

However, this is not ideal for me. I would like to run migrations from a deployment script on my ci server. I found this article explaining how to do this using migrate.exe but this seems to always run the seed. This is even when there are no migrations to apply.

Do I need to check programmatically within the Seed method whether any migrations have been run? How do I do this?

like image 488
George Mauer Avatar asked Mar 22 '13 21:03

George Mauer


1 Answers

Use DbMigrator to manually run Update() only if there are pending migrations. It was introduced in Entity Framework 5.0.

private void MigrateAndSeedDbIfSchemaIsOutdated()
{
    // Disable initializer.
    Database.SetInitializer<MyContext>(null);

    // Make sure database exists.
    using (var db = new MyContext())
    {
        db.Database.Initialize(false);
    }

    var migrator = new DbMigrator(new MyConfiguration());

    if (migrator.GetPendingMigrations().Any())
    {
        // Run migrations and seed.
        migrator.Update();
    }
}
like image 54
angularsen Avatar answered Nov 11 '22 21:11

angularsen