Efcore: Suggestion: programmatically update to a specific migration

Created on 4 Oct 2017  路  4Comments  路  Source: dotnet/efcore

I can already use PowerShell to update to a specific migration:

Update-Database -Migration ExampleMigration

I can also programmatically apply all pending migrations using the Migrate() extension method:

dbContext.Database.Migrate();

It would be nice if there was an overload of Migrate() that took a specific migration to update to. Right now this is not possible without digging into infrastructure classes like Migrator that aren't meant for public use.

Use cases:

  • Automated testing/validation of migration Up/Down code.
  • Abstracting database migration details away from QA/IT who don't know/don't care about EF.
closed-by-design

Most helpful comment

Workaround

As mentioned, you can do this by dropping down to some lower-level components.

dbContext.GetService<IMigrator>().Migrate(targetMigration);

Use the constant Migration.InitialDatabase to revert all migrations.

All 4 comments

@jessebarocio Could you explain a bit more about what the situation is when you don't want the database updated to the latest migration, given that this is the one that matches the model as currently built by the context?

@ajcvickers sure, here are the two use cases I came up with.

I want to run an integration test that rolls back all migrations and then updates to the latest migration. This makes sure team members haven't broken the migration path (by, for example, tweaking code in a migration's Up() or Down() methods). If a developer does break migrations it can be a pain to fix. Running this as an integration test during CI builds would make detection easier.

The other use case I thought of is more specific to my organization. Right now in projects that don't use EF our QA department runs a utility to rollback/update the database to a specific version so they have a clean set of test data to work with. It would be nice to have a way to create this same type of utility for projects that do use EF.

Workaround

As mentioned, you can do this by dropping down to some lower-level components.

dbContext.GetService<IMigrator>().Migrate(targetMigration);

Use the constant Migration.InitialDatabase to revert all migrations.

Triage: since there is a way to do this without using internal surface already and because we think that adding it to the top-level API surface may cause confusion/additional unneeded decision points, we have decided to not to this. However, we will add a note to the docs for people who do need this low-level control: https://github.com/aspnet/EntityFramework.Docs/issues/518

Was this page helpful?
0 / 5 - 0 ratings