Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save danielwertheim/4167897 to your computer and use it in GitHub Desktop.

Select an option

Save danielwertheim/4167897 to your computer and use it in GitHub Desktop.
ReallyDoDropCreateDatabaseIfModelChanges
public class ReallyDoDropCreateDatabaseIfModelChanges<TContext> : IDatabaseInitializer<TContext> where TContext : DbContext
{
protected const string Sql =
"if (select DB_ID('{0}')) is not null\r\n"
+ "begin\r\n"
+ "alter database [{0}] set offline with rollback immediate;\r\n"
+ "alter database [{0}] set online;\r\n"
+ "drop database [{0}];\r\n"
+ "end";
public virtual void InitializeDatabase(TContext context)
{
if (DbExists(context))
{
if (context.Database.CompatibleWithModel(false))
return;
DropDatabase(context);
}
context.Database.Create();
Seed(context);
context.SaveChanges();
}
protected virtual bool DbExists(TContext context)
{
using (new TransactionScope(TransactionScopeOption.Suppress))
{
return context.Database.Exists();
}
}
protected virtual void DropDatabase(TContext context)
{
context.Database.ExecuteSqlCommand(string.Format(Sql, context.Database.Connection.Database));
}
protected virtual void Seed(TContext context) { }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment