我正在尝试调试我的源代码
Exception: System.InvalidOperationException
Message: Internal .Net Framework Data Provider error 1.
StackTrace: at System.Data.ProviderBase.DbConnectionInternal.PrePush(Object expectedOwner) at System.Data.ProviderBase.DbConnectionPool.PutObject(DbConnectionInternal obj, Object owningObject) at System.Data.ProviderBase.DbConnectionInternal.CloseConnection(DbConnection owningObject, DbConnectionFactory connectionFactory) at System.Data.SqlClient.SqlConnection.CloseInnerConnection() at System.Data.SqlClient.SqlConnection.Close() at System.Data.SqlClient.SqlConnection.Dispose(Boolean disposing) at System.ComponentModel.Component.Dispose()
我在日志文件中看到的错误,我认为这些错误会导致 502 错误。我与数据库的所有交互(我试图以最老派的方式进行)就像
public List<VersionInfo> GetAllVersions ( )
{
List<VersionInfo> Versions = new List<VersionInfo>();
using (SqlConnection con = new SqlConnection(SurveyDbModel._conn))
{
con.Open();
using (SqlCommand cmd = new SqlCommand("GetAllVersions",con))
{
cmd.CommandType = CommandType.StoredProcedure;
using (SqlDataReader dataReader = cmd.ExecuteReader())
{
while (dataReader.Read())
{
Versions.Add(new VersionInfo
{
Id = !dataReader.IsDBNull(0) ? dataReader.GetInt32(0) : default(int),
Title = !dataReader.IsDBNull(1) ? dataReader.GetString(1) : String.Empty
});
}
}
}
con.Close();
}
return Versions;
}
我是否正确地使用了using
?有什么嵌套错误吗?
最佳答案
您收到的错误不是因为连接处理无效。通过使用 using() { } 范围,您可以很好地实现它,因为连接将在离开范围时自动处理。然而,GetAllVersions 不是一个有效的操作,要么是因为过程逻辑错误,要么是因为它不存在,这就是错误的原因。
如果您实际上有一个以这种方式命名的存储过程(这不是好的做法),您应该在它前面加上 exec,例如:
exec GetAllVersions
但是,您应该重命名它以遵循通用准则: 执行 usp_GetAllVersions
或类似内容,请参阅 https://www.mssqltips.com/sqlservertutorial/169/naming-conventions-for-sql-server-stored-procedures/有关良好命名的示例。
编辑 1: 我建议您将存储过程与问题一起发布,或者检查存储过程是否可在用户 session 中运行。我的钱在于它不是。
关于c# - 不留下未关闭的连接的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35999477/