Database in use error with Entity Framework 4 Code First

21,090

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.

Share:
21,090
ProfK
Author by

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, 2020

Comments

  • ProfK
    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>, where TocratesDb is my derived DbContext.

    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
    ProfK about 13 years
    I 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
    Ladislav Mrnka about 13 years
    It provides the hook - you can implement custom IDatabaseInitializer and you can register it in context.Database.SetInitializer().
  • ProfK
    ProfK about 13 years
    Ah yes, I actually found that a short while ago, and am trying it now.
  • ProfK
    ProfK about 13 years
    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.
  • sam1132
    sam1132 over 12 years
    This 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
    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
    sam1132 over 12 years
    @ladislav, I entered what seems to work for me in a separate answer. Am I missing something?
  • sam1132
    sam1132 over 12 years
    @ladislav clearly I did miss something with what I was doing, thank you for your patience.
  • Jon
    Jon about 11 years
    This errors for me as it says database already exists using VS2012
  • Dave Jellison
    Dave Jellison about 11 years
    Do you have access to master when you're authenticating? That's critical for USE master DROP DATABASE
  • ashutosh raina
    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
    ProfK almost 11 years
    This 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
    Nullius almost 11 years
    Actually, 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
    Jowen over 10 years
    Using 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
    Ladislav Mrnka over 10 years
    @Jowen: It seems like your database wasn't really dropped and recreated but just modified.
  • RaoulRubin
    RaoulRubin over 10 years
    Great comment. Fixed my problems with EF 6 code first database creation when issuing ALTER DATABASE to SET ALLOW_SNAPSHOT_ISOLATION ON. Thanks!
  • Jeff Pearce
    Jeff Pearce about 10 years
    I 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
    Dav almost 10 years
    Love SO for finding little time-saving gems like this one... Thanks for sharing!
  • WernerCD
    WernerCD over 9 years
    Never THOUGHT to look there. Ugh.
  • Corwin
    Corwin over 9 years
    It also makes sense to switch DB back to multi-user mode after re-creation, like: context.Database.ExecuteSqlCommand(TransactionalBehavior.DoN‌​otEnsureTransaction, "ALTER DATABASE [" + context.Database.Connection.Database + "] SET MULTI_USER WITH ROLLBACK IMMEDIATE");
  • Jowen
    Jowen over 9 years
    @ashutoshraina Try to add the TransactionalBehavior.DoNotEnsureTransaction param to the ExecuteSqlCommand method. More info: stackoverflow.com/questions/21699075/…
  • 4imble
    4imble about 8 years
    This was extremely convenient for me to use. Just dropped it one line before my context.Database.Delete() call and it sorted my problem.