Is the correct way to leave no unclosed connections?

Viewed 271

I'm trying to debug the source of my

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()

errors that I'm seeing in my log files and that I believe are leading to 502 errors. All my interactions with the database (I'm trying to do this in the most old-school way possible) are like

    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;
    }

Am I doing the usings right? Anything nested wrong?

1 Answers
Related