Created
November 29, 2012 09:54
-
-
Save danielwertheim/4167897 to your computer and use it in GitHub Desktop.
ReallyDoDropCreateDatabaseIfModelChanges
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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