Deleting database from C#

Take a look at the SMO (SQL Server Management Objects) .NET wrappers.

These allow you to manage all aspects of SQL Server from code, including deleting of databases.

The database object has a Drop method.

The code below is to illustrate how you could use the object model, though I have not tested it:

var server = new Server(serverName); // Can use overload that specifies 

foreach (Database db in server.Databases)
{
     if (db.Name.ToLower().Contains(testDatabaseIdentifier))
     {
          databasesToDelete.Add(db.Name);
     }
}
databasesToDelete.ForEach(x =>
{
     Database db = new Database(server, x);
     db.Refresh();
     db.Drop();
});

Try with this:

sqlCommandText = "DROP DATABASE [NAME]";
sqlCommand = new SqlCommand(sqlCommandText , connection);
sqlCommand.ExecuteNonQuery();

I think this would help.


Instead of using the Database type to delete a database in TestCleanup, I would recommend to use the Microsoft.SqlServer.Management.Smo.Server.KillDatabase method. In addition, this will close all existing SQL connections before the database is deleted. Thus your unit tests (or rather integration tests) might leave connections open and this will have no effect on the cleanup method.

var server = new Server(SqlServerName);
server.KillDatabase(DatabaseName);