为什么sqlConnection.Close()没有关闭登录?

Gar*_*wen 3 sql-server database-connection smo

我们有单元测试来测试我们的数据库安装和卸载功能是否成功运行.单元测试使用SqlClient.SqlConnection类检查之前,期间和之后的数据库内容.

我们的问题是在使用SqlClient.SqlConnection之后,卸载的drop login部分失败,因为它声称用户当前已登录.即使我们调用了SqlConnection.Close(),登录似乎仍然是打开的.

我们的代码看起来有点像这样:

InstallTables();  // function uses smo to create tables in a database.
string connString = CreateLogin("userName", "password");  // create login with smo

// Test the returned connection string connects to the database
using (SqlConnection con = new SqlConnection(connString))
{
    con.Open();
    //test code to read the DB version out of a table
    //Dispose calls con.Close() - I have also tried calling it explicitly
}

DropTables();  // uses smo to drop tables from the database
DropLogin("userName", "password");   // uses smo to drop the login
Run Code Online (Sandbox Code Playgroud)

DropLogin失败,出现以下异常:System.Data.SqlClient.SqlException:无法在用户当前登录时删除登录'engageSecurity_unittest_1294​​18264074692569'.

如果我在DropLogin之后删除所有SqlConnection代码,那么一切运行正常.

当我调用SqlConnection.Close()时,有谁知道用户为什么没有注销?

这与连接池有关吗?

Jus*_*ner 8

除非您在连接字符串中明确禁用连接池,否则我的猜测是,即使您正在处理连接,它仍然在连接池中存活(如果您决定重新使用它):

SQL Server连接池(ADO.NET)

尝试禁用连接池(通过添加Pooling=false;连接字符串)并查看会发生什么.