Skip to content

Instantly share code, notes, and snippets.

@jpogran
Created May 9, 2011 18:43
Show Gist options
  • Save jpogran/963091 to your computer and use it in GitHub Desktop.
Save jpogran/963091 to your computer and use it in GitHub Desktop.
ef code first db creation methods
public static class EFCodeFirstMethods
{
public static void DumpDbCreationScriptToFile(DbContext context)
{
var script = CreateDbScript(context);
// C:\Users\james\code\work\impact\phyweb\src\IRX.Web.UI\
var appDomainPath = AppDomain.CurrentDomain.BaseDirectory;
var scriptPath = GetScriptsDirectory(appDomainPath);
var scriptName = Path.Combine(scriptPath, "db_create.sql");
WriteTextToFile(script, DateTime.UtcNow.ToString("MM-dd-yyyy-H-mm-ss"), scriptName);
}
private static string GetScriptsDirectory(string appDomainPath)
{
var oneLevelUp= Directory.GetParent(appDomainPath);
var twoLevelUp= Directory.GetParent(oneLevelUp.FullName);
var threeLevelUp= Directory.GetParent(twoLevelUp.FullName);
return Path.Combine(threeLevelUp.FullName, "scripts");
}
public static void WriteTextToFile(string text, string timestamp, string filename)
{
using (StreamWriter sw = File.CreateText(filename))
{
sw.WriteLine(timestamp);
sw.Write(text);
}
}
public static string CreateDbScript(DbContext context)
{
var script = ((IObjectContextAdapter)context).ObjectContext.CreateDatabaseScript();
return script;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment