Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Cannot drop database because it is currently in use". How to fix?

Having this simple code I get "Cannot drop database "test_db" because it is currently in use" (CleanUp method) as I run it.

[TestFixture] public class ClientRepositoryTest {     private const string CONNECTION_STRING = "Data Source=.;Initial Catalog=test_db;Trusted_Connection=True";     private DataContext _dataCntx;      [SetUp]     public void Init()     {         Database.SetInitializer(new DropCreateDatabaseAlways<DataContext>());         _dataCntx = new DataContext(CONNECTION_STRING);         _dataCntx.Database.Initialize(true);     }      [TearDown]     public void CleanUp()     {         _dataCntx.Dispose();         Database.Delete(CONNECTION_STRING);     } } 

DataContext has one property like this

 public DbSet<Client> Clients { get; set; } 

How can force my code to remove database? Thanks

like image 741
YMC Avatar asked Aug 10 '11 00:08

YMC


People also ask

Can't drop a database because it is in use?

Start by right-clicking Replication in Object Explorer, and choosing Publisher Properties: In the Publisher Properties window, select the Publication Databases page: Here you can deselect the database that you're trying to drop. Once you've saved this, you should be able to drop your database.

How do I drop a database when in use?

Drop Database in SQL Server Using SQL Server Management Studio. Connect to SQL Server Management Studio; expand Database Node -> Right click the Databases which you want to Drop -> Select Delete from the drop-down menu to open up Delete Object dialog box as shown in the snippet below.

How do I force a database to drop in SQL Server?

To remove a database from the current server without deleting the files from the file system, use sp_detach_db. USE master; ALTER DATABASE [databasename] SET SINGLE_USER WITH ROLLBACK IMMEDIATE; DROP DATABASE [databasename] ; Note, database backups will not be deleted as part of the process documented above.

Can't drop existing database SQL?

If you want to delete the database, you will get this error if there is an open session on the database. First, set the database to single_user mode. Then you can delete it.


1 Answers

The problem is that your application probably still holds some connection to the database (or another application holds connection as well). Database cannot be deleted where there is any other opened connection. The first problem can be probably solved by turning connection pooling off (add Pooling=false to your connection string) or clear the pool before you delete the database (by calling SqlConnection.ClearAllPools()).

Both problems can be solved by forcing database to delete but for that you need custom database initializer where you switch the database to single user mode and after that delete it. Here is some example how to achieve that.

like image 118
Ladislav Mrnka Avatar answered Sep 28 '22 09:09

Ladislav Mrnka