Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 260
Daniel Goldberg Avatar asked Oct 28 '25 22:10

Daniel Goldberg


1 Answers

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.

like image 147
Guru Stron Avatar answered Oct 30 '25 13:10

Guru Stron