I am using MVC 4, Entity Framework 5, and the Code First approach.
When I make changes to my model and run the application I get an error about not being able to drop the database because it is in use.
To solve this, I've implemented my own IDatabaseInitializer
to force a single connection like this:
public class ForceDropCreateDatabaseInitializer<T> : IDatabaseInitializer<T> where T : DbContext, new()
{
public ForceDropCreateDatabaseInitializer(Action<T> seed = null)
{
Seed = seed ?? delegate { };
}
public Action<T> Seed { get; set; }
public void InitializeDatabase(T context)
{
if (context.Database.Exists())
{
string databaseName = context.Database.Connection.Database;
string alterStatement = "ALTER DATABASE [{0}] SET SINGLE_USER WITH ROLLBACK IMMEDIATE";
string dropStatement = "USE [master] DROP DATABASE [{0}]";
context.Database.ExecuteSqlCommand(alterStatement, databaseName);
context.Database.ExecuteSqlCommand(dropStatement, databaseName);
}
context.Database.Create();
Seed(context);
}
}
But now I am getting a permissions error on this line:
context.Database.ExecuteSqlCommand(alterStatement, databaseName);
The exception message:
User does not have permission to alter database '@p0', the database does not exist, or the database is not in a state that allows access checks.
ALTER DATABASE statement failed.
I presume @p0 is used because I am using parameters. How can I avoid this error and successfully drop and create my database each time I make model changes?