Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

255
Visualizações
Run code after all EF Core migrations are applied

EF Core 5 has various events, but they relate to DbContext. There are no events related to migrations (Migration).

I want to run custom code after all migrations are applied - whether triggered by code (context.Database.Migrate()) or the CLI (dotnet ef database update).

The workaround is to add an "empty" migration, and place my code in its Up method. But I would need to do that every time I add a migration.

Assuming there's no event or hook I can use (is there?), how can I run custom code after all migrations are applied?

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Here's a workaround.

[DbContext(typeof(MyContext))]
[Migration("99999999999999_Last1")]
public class Last1 : Migration {
  protected override void Up(MigrationBuilder migrationBuilder) {
    Task.Run(() => callPostMigrationCodeThatIsIdempotent()).GetAwaiter().GetResult();
    migrationBuilder.DeleteData(HistoryRepository.DefaultTableName, nameof(HistoryRow.MigrationId), "string", "99999999999999_Last2", null);
  }
}

[DbContext(typeof(MyContext))]
[Migration("99999999999999_Last2")]
public class Last2 : Migration {
  protected override void Up(MigrationBuilder migrationBuilder) {
    Task.Run(() => callPostMigrationCodeThatIsIdempotent()).GetAwaiter().GetResult();
    migrationBuilder.DeleteData(HistoryRepository.DefaultTableName, nameof(HistoryRow.MigrationId), "string", "99999999999999_Last1", null);
  }
}

There are two "last" migrations:

  • their ids are chosen so they run last ("99999999999999")
  • both call the custom code, which must be idempotent
  • each deletes the other from the history table
  • they use Task.Run for async over sync

During each run one or the other runs the custom code, and deletes the other from the history table. On the next run the opposite would occur.

The same double setup can be used for a pre-migration hook.

There's an open backlog item on the repo.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda