tabs ↹ over ␣ ␣ ␣ spaces

by Jiří {x2} Činčura

Generating Entity Framework Core Migrations script from code

6 Oct 2017 1 mins 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 .NET, C# and Firebird expert. He focuses on data and business layers, language constructs, parallelism, databases and performance. For almost two decades he contributes to open-source, i.e. FirebirdClient. He works as a senior software engineer for Microsoft. Frequent speaker and blogger at www.tabsoverspaces.com.