Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply EF core migrations one by one in code

I need to apply Entity Framework Core migrations one by one in code, i can call the await dbContext.Database.MigrateAsync(); but it applies all the pending migrations in one block.

Is there an extension or other method to apply the migrations just one by one or selecting the name of the migration to apply?

like image 214
animalito maquina Avatar asked Mar 01 '18 11:03

animalito maquina


People also ask

How do I apply ef core migrations?

Migrations are enabled by default in EF Core. They are managed by executing commands. If you have Visual Studio, you can use the Package Manager Console (PMC) to manage migrations. Alternatively, you can use a command line tool to execute Entity Framework CLI commands to create a migration.

How do I code my first migration to an existing database?

Run the Add-Migration InitialCreate command in Package Manager Console. This creates a migration to create the existing schema. Comment out all code in the Up method of the newly created migration. This will allow us to 'apply' the migration to the local database without trying to recreate all the tables etc.

How do I add a migration to multiple DbContext?

One way to create multiple migration sets is to use one DbContext type per provider. Specify the context type when adding new migrations. You don't need to specify the output directory for subsequent migrations since they are created as siblings to the last one.


1 Answers

There is a IMigrator service with a Migrate(string targetMigration) method that receives the migration name, this method is used by the Migrate() extension. From a DbContext instance it can be used as:

await dbContext.Database.GetInfrastructure().GetService<IMigrator>().MigrateAsync(targetMigrationName);

The pending migrations names can be queried by this extension:

var pending = dbContext.Database.GetPendingMigrations();
like image 87
animalito maquina Avatar answered Sep 30 '22 15:09

animalito maquina