SqlDataReader InvalidOperationException

好久不见. 提交于 2019-12-25 18:18:07

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/23187029/sqldatareader-invalidoperationexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!