How to close all existing connections to a DB programmatically How to close all existing connections to a DB programmatically database database

How to close all existing connections to a DB programmatically


It does seem that Entity Framework keeps a connection to the database. You can see it be executing sp_who2 in SQL Server Management Studio where Entity Framework is listed as EntityFrameworkMUE under ProgramName.

You don't have to use "raw" sql statements to disconnect the active connections though, it can be solved this way as well:

Server server = new Server(".\\SQLEXPRESS");Database database = new Database(server, dbName);database.Refresh();server.KillAllProcesses(dbName);database.DatabaseOptions.UserAccess = DatabaseUserAccess.Single;database.Alter(TerminationClause.RollbackTransactionsImmediately);//restore.SqlRestore(server);


You get that error when you are call Open() on a connection twice. You should make all SqlConnection objects you create inside using blocks and only open them once.

If you are reusing connections "to make it faster" .NET already does that by default for you via Connection Pooling but you must dispose of the connection object to make it work.


You need to dispose the reader, the command and the connection. Your reader is not disposed. This code snippet will guarantee that the connection is closed even if there are exceptions thrown during the read process.

using (var conn = new SqlConnection("...")){    conn.Open();    using (var cmd = conn.CreateCommand())    {        cmd.CommandText = "Command text.....";        using (var reader = cmd.ExecuteReader())        {           ....        }    }}