tabs ↹ over ␣ ␣ ␣ spaces

by Jiří {x2} Činčura

Getting database script from DbContext (Code First)

6 May 2011 Entity Framework

I was speaking at Gopas Teched few days ago and there was a good question from audience about how to get the SQL script the DbContext is using to create database.

I never thought about it as I always create database in ER tool as it provides more features (like triggers, stored procedures etc.). But I remembered I implemented this method in .NET provider for Firebird. So it has to be somewhere.

The method is called CreateDatabaseScript and it’s on ObjectContext. So it was easy to expose it directly from DbContext, because it has ObjectContext under the hood (you can access it via IObjectContextAdapter).

public static string CreateDatabaseScript(this DbContext context)
	return ((IObjectContextAdapter)context).ObjectContext.CreateDatabaseScript();

Hope the questioner will find this blog post.

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