Database in use error with Entity Framework 4 Code First
Solution 1
Your current context must have an opened connection to be able to drop the database. The problem is that there can be other opened connections which will block your db initializer. One very nice example is having opened any table from your database in management studio. Another possible problem can be opened connections in the connection pool of your application.
In MS SQL this can be avoided for example by switching DB to SINGLE USER mode and forcing all connections to be closed and incomplete transactions rolled back:
ALTER DATABASE Tocrates SET SINGLE_USER WITH ROLLBACK IMMEDIATE
You can create a new intializer which will first call this command and then drops the database. Be aware that you should handle a database connection by yourselves because ALTER DATABASE
and DROP DATABASE
must be called on the same connection.
Edit:
Here you have example using Decorator pattern. You can modify it and initialize inner initializer inside the constructor instead of passing it as a parameter.
public class ForceDeleteInitializer : IDatabaseInitializer<Context>
{
private readonly IDatabaseInitializer<Context> _initializer;
public ForceDeleteInitializer(IDatabaseInitializer<Context> innerInitializer)
{
_initializer = innerInitializer;
}
public void InitializeDatabase(Context context)
{
context.Database.SqlCommand("ALTER DATABASE Tocrates SET SINGLE_USER WITH ROLLBACK IMMEDIATE");
_initializer.InitializeDatabase(context);
}
}
Solution 2
I found in EF 6 this fails with an ALTER DATABASE statement not allowed within multi-statement transaction
error.
The solution was to use the new transaction behavior overload like this:
context.Database.ExecuteSqlCommand(TransactionalBehavior.DoNotEnsureTransaction, "ALTER DATABASE [" + context.Database.Connection.Database + "] SET SINGLE_USER WITH ROLLBACK IMMEDIATE");
Solution 3
I had the same issue.
I resolved it by closing a connection open under the Server Explorer view of Visual Studio.
Solution 4
I realize this is dated but I couldn't get the accepted solution working so I rolled a quick solution...
using System;
using System.Data.Entity;
namespace YourCompany.EntityFramework
{
public class DropDatabaseInitializer<T> : IDatabaseInitializer<T> where T : DbContext, new()
{
public DropDatabaseInitializer(Action<T> seed = null)
{
Seed = seed ?? delegate {};
}
public Action<T> Seed { get; set; }
public void InitializeDatabase(T context)
{
if (context.Database.Exists())
{
context.Database.ExecuteSqlCommand("ALTER DATABASE [" + context.Database.Connection.Database + "] SET SINGLE_USER WITH ROLLBACK IMMEDIATE");
context.Database.ExecuteSqlCommand("USE master DROP DATABASE [" + context.Database.Connection.Database + "]");
}
context.Database.Create();
Seed(context);
}
}
}
This works for me and supports seeding easily.
Solution 5
In Visual Studio 2012, the SQL Server Object Explorer window can hold a connection to the database. Closing the window and all windows opened from it releases the connection.
ProfK
I am a software developer in Johannesburg, South Africa. I specialise in C# and ASP.NET, with SQL Server. I have, in some way or another, been involved in software development for about eighteen years, but always learning something new. At the moment that is WPF and MVVM.
Updated on November 28, 2020Comments
-
ProfK over 3 years
I have an MVC3 and EF 4 Code First application, which is configured to change the DB when the model changes, by setting the DB Initializer to a
DropCreateDatabaseIfModelChanges<TocratesDb>
, whereTocratesDb
is my derivedDbContext
.I have now made a change to the model, by adding properties to a class, but when EF tries to drop and recreate the DB, I get the following error:
Cannot drop database "Tocrates" because it is currently in use.
I have absolutely no other connections anywhere open on this database. I assume that my cDbContext still has an open connection to the database, but what can I do about this?
NEW: Now my problem is how to re-create the database based on the model. By using the more general IDatabaseInitializer, I lose that and have to implement it myself.
-
ProfK about 13 yearsI have no SSMS connections open on the DB, but my problem is the Initializer offers no proper hook where I can execute your recommended code, not to mention I should not be doing the frameworks housekeeping.
-
Ladislav Mrnka about 13 yearsIt provides the hook - you can implement custom
IDatabaseInitializer
and you can register it incontext.Database.SetInitializer()
. -
ProfK about 13 yearsAh yes, I actually found that a short while ago, and am trying it now.
-
ProfK about 13 yearsNow my problem is how to re-create the database based on the model. By using the more general IDatabaseInitializer, I lose that and have to implement it myself.
-
sam1132 over 12 yearsThis answer is OK. But doesn't seem to work real well with seeding. Also, the innerInitializer stuff is not necessary if you subclass the Initialization strategy you want.
-
Ladislav Mrnka over 12 years@mcl: This answer is about deleting database in use. I don't know what you mean by seeding - you can seed data in another initializer passed to this wrapper. Initializer stuff is needed because subclassing initializer will not help - you must run custom SQL prior to running initializers code - that is not possible with subclassed initializer because
InitializeDatabase
method is not virtual. -
sam1132 over 12 years@ladislav, I entered what seems to work for me in a separate answer. Am I missing something?
-
sam1132 over 12 years@ladislav clearly I did miss something with what I was doing, thank you for your patience.
-
Jon about 11 yearsThis errors for me as it says database already exists using VS2012
-
Dave Jellison about 11 yearsDo you have access to master when you're authenticating? That's critical for USE master DROP DATABASE
-
ashutosh raina about 11 years@DaveJellison I tried your solution but it gives me System.Data.SqlClient.SqlException : ALTER DATABASE statement not allowed within multi-statement transaction. Any ideas ?
-
ProfK almost 11 yearsThis code will, however, always drop and create the database. I think it's going to be challenging to convert it to only do this if the model changes.
-
Nullius almost 11 yearsActually, you should wrap the database name variable in brackets like
context.Database.ExecuteSqlCommand("ALTER DATABASE [" + context.Database.Connection.Database + "] SET SINGLE_USER WITH ROLLBACK IMMEDIATE");
Otherwise, I received an error complaining about the WITH keyword. -
Jowen over 10 yearsUsing this example, I couldn't get in the database myself anymore. I fixed that by setting it back to MULTI_USER in the end of my script.
-
Ladislav Mrnka over 10 years@Jowen: It seems like your database wasn't really dropped and recreated but just modified.
-
RaoulRubin over 10 yearsGreat comment. Fixed my problems with EF 6 code first database creation when issuing ALTER DATABASE to SET ALLOW_SNAPSHOT_ISOLATION ON. Thanks!
-
Jeff Pearce about 10 yearsI have implemented this but on occasion I get the error System.Data.SqlClient.SqlException was unhandled by user code HResult=-2146232060 Message=ALTER DATABASE statement not allowed within multi-statement transaction.
-
Dav almost 10 yearsLove SO for finding little time-saving gems like this one... Thanks for sharing!
-
WernerCD over 9 yearsNever THOUGHT to look there. Ugh.
-
Corwin over 9 yearsIt also makes sense to switch DB back to multi-user mode after re-creation, like: context.Database.ExecuteSqlCommand(TransactionalBehavior.DoNotEnsureTransaction, "ALTER DATABASE [" + context.Database.Connection.Database + "] SET MULTI_USER WITH ROLLBACK IMMEDIATE");
-
Jowen over 9 years@ashutoshraina Try to add the TransactionalBehavior.DoNotEnsureTransaction param to the ExecuteSqlCommand method. More info: stackoverflow.com/questions/21699075/…
-
4imble about 8 yearsThis was extremely convenient for me to use. Just dropped it one line before my context.Database.Delete() call and it sorted my problem.