Created
May 31, 2017 09:18
-
-
Save code-atom/db4ccd0cad93e9506d1d87529c887a66 to your computer and use it in GitHub Desktop.
Forcefully delete Database if database is already in use.
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
/// <summary> | |
/// Database Initializer that will Drop/Create databases that are currently in use | |
/// </summary> | |
/// <typeparam name="TContext">Data Context</typeparam> | |
public class ForceDeleteInitializer<TContext> : IDatabaseInitializer<TContext> where TContext : DbContext | |
{ | |
private readonly IDatabaseInitializer<TContext> _initializer; | |
public ForceDeleteInitializer() | |
{ | |
_initializer = new DropCreateDatabaseAlways<TContext>(); | |
} | |
public ForceDeleteInitializer(IDatabaseInitializer<TContext> innerInitializer) | |
{ | |
_initializer = innerInitializer; | |
} | |
public void InitializeDatabase(TContext context) | |
{ | |
if (context.Database.Exists()) | |
{ | |
context.Database.ExecuteSqlCommand(TransactionalBehavior.DoNotEnsureTransaction, string.Format("ALTER DATABASE {0} SET SINGLE_USER WITH ROLLBACK IMMEDIATE", context.Database.Connection.Database)); | |
} | |
_initializer.InitializeDatabase(context); | |
if (context is IDbContextSeeder) | |
{ | |
(context as IDbContextSeeder).Seed(); | |
} | |
if (context.Database.Exists()) | |
{ | |
context.Database.ExecuteSqlCommand(TransactionalBehavior.DoNotEnsureTransaction, string.Format("ALTER DATABASE {0} SET MULTI_USER", context.Database.Connection.Database)); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Reference link :-
http://fusioncomputing.com/blog/post/ef6-and-execute-sql-command