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
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With