Question

I have a SqlDB.dll that has the function:

         public SqlDataReader getEnumValues(int enumId)
    {
        SqlDataReader reader = null;
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            connection.Open();
            SqlCommand command =
                new SqlCommand(
                    "SELECT * FROM [EnumValue] WHERE enumId LIKE '" + enumId + "';",
                    connection);
            reader = command.ExecuteReader();
            //if(reader.Read())
            //    Debug.WriteLine("Inside sqlDb->getEnumValues command = " + command.CommandText + " reader[name] = " + reader["name"].ToString() + " reader[value] = " + reader["value"].ToString() + " reader[description] = " + reader["description"].ToString());
        }
        //reader.Close();
        return reader;
    }

As you can see I have tried closing the reader before returning it, and also I read the data inside and it's ok. I'm using the function like this:

 using (SqlDataReader getEnumValuesReader = (SqlDataReader)getEnumValues.Invoke(sqlDB, getEnumValuesForEnumParam))
                    {
                        Debug.WriteLine("Success getEnumValues -- ");

                        if (getEnumValuesReader.HasRows)
                        {
                            while (getEnumValuesReader.Read())        //Loop throw all enumValues and add them to current enum
                            {
                                try
                                {
                                    values.Add(new Model.EnumValue(getEnumValuesReader["name"].ToString(), getEnumValuesReader["value"].ToString(), getEnumValuesReader["description"].ToString()));
                                    Debug.WriteLine("Value[0].name = " + values[0].Name);
                                }
                                catch (Exception ex)
                                {
                                    Debug.WriteLine("Error in building new EnumValue: " + ex.Message);
                                }
                            }
                        }

                    }

and I'm getting exception of type 'System.InvalidOperationException'

I'm guessing it has something to do with the Sqldatareader being passed.

Was it helpful?

Solution

The SQL reader cannot exist outside the context of the SQL connection. Your connection is being disposed in your method, so your returned reader cannot fetch any data in the calling method.

the best option is to return the values from the reader instead of the reader. It is not good practice to pass around readers, which means the underlying connection etc. Is open and undisposed.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top