tabs ↹ over ␣ ␣ ␣ spaces

by Jiří {x2} Činčura

Generating Entity Framework Core Migrations script from code

6 Oct 2017 Entity Framework Core

Creating script for migrations in command line is easy. Just execute dotnet ef migrations script and you’re done. But what if you want to do this in the code?

Executing migrations from code is easy, because there’s directly a method for it: DbContext.Database.Migrate. Sadly, there isn’t a direct method for creating a script. That doesn’t mean it can’t be done, of course. The important piece we need is implementation of IMigrator. Once we have it it’s easy again thanks to the GenerateScript method.

var script = db.GetService<IMigrator>().GenerateScript();

I suppose this scenario is not common enough, thus some plumbing is required. On the other hand it’s probably even easier than in Entity Framework 6.

Profile Picture Jiří Činčura is an independent developer focusing on data and business layers, language constructs, parallelism and databases. Specifically Entity Framework, asynchronous and parallel programming, cloud and Azure. He's Microsoft Most Valuable Professional and you can read his articles, guides, tips and tricks at www.tabsoverspaces.com.