Search code examples
c#entity-framework-coreef-code-firstnpgsql.net-7.0

Is there a way in EF core to use a dbContext to generate migration script


Looking for a code first way of using a context to generate the sql script to migrate from one specific migration to another. I cant seem to find this online.

something like

context.Database.GenerateMigrationScript(‘migration5’ , ‘migration7’) 

that returns a string of sql script

Thank you!


Solution

  • You can use the EF Core migrator (IMigrator) infrastructure to programmatically generate the migration. To access it you can use AccessorExtensions.GetService<TService> method:

    MyAppDbContext ctx = ...
    var migrator = ctx.GetService<IMigrator>();
    var generateScript = migrator.GenerateScript("migration5", "migration7"); 
    

    P.S.

    Also you can use dotnet ef CLI tool which has dotnet ef migrations script command (accepts from and to parameters too):

    Generates a SQL script from migrations.