I'm trying to create a database, run some tests on it, then drop the database:
namespace TestConsole
{
class Program
{
static void Main(string[] args)
{
const string testConnectionString = @"Server=localhost\SQL2014EXPRESS64; Database=RepoTest; Trusted_Connection=True;";
const string masterConnectionString = @"Server=localhost\SQL2014EXPRESS64; Database=master; Trusted_Connection=True;";
// connect to master and create RepoTest db
using (var connection = new SqlConnection(masterConnectionString))
using (var command = new SqlCommand("CREATE DATABASE RepoTest", connection))
{
connection.Open();
command.ExecuteNonQuery();
}
// connect to RepoTest and create some new tables
using (var connection = new SqlConnection(testConnectionString))
using (var command = new SqlCommand("CREATE TABLE Test(ID INT NOT NULL)", connection))
{
connection.Open();
command.ExecuteNonQuery();
}
// connect to master and delete RepoTest db
using (var connection = new SqlConnection(masterConnectionString))
using (var command = new SqlCommand("DROP DATABASE RepoTest", connection))
{
connection.Open();
command.ExecuteNonQuery();
}
}
}
}
but I get this Exception when trying to drop the test database:
An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Additional information: Cannot drop database "RepoTest" because it is currently in use.
But I expected it to no longer be in use as the part that was using that database was in a using block so I expected the connection to be closed and the operation to be complete, if this isn't the case is there a command I can use to drop the database when its finished its current process?