This error occurs when there is an attempt to execute a new query on a database connection before the previous query's DataReader has been closed.

To resolve this error, you can do the following:

  1. Make sure to close any open DataReader before executing a new query on the same connection.

  2. Use the SqlDataReader.NextResult() method to move to the next result set if you need to execute multiple queries on the same connection.

  3. Use the using statement to automatically dispose of the DataReader and close the connection after the query has been executed.

Example:

using (SqlConnection connection = new SqlConnection(connectionString))
{
    connection.Open();
    
    using (SqlCommand command = new SqlCommand("SELECT * FROM Table1", connection))
    {
        using (SqlDataReader reader = command.ExecuteReader())
        {
            while (reader.Read())
            {
                // do something with the data
            }
        }
    }
    
    // execute another query after closing the previous DataReader
    using (SqlCommand command = new SqlCommand("SELECT * FROM Table2", connection))
    {
        using (SqlDataReader reader = command.ExecuteReader())
        {
            while (reader.Read())
            {
                // do something with the data
            }
        }
    }
}
``
C# There is already an open DataReader associated with this Connection which must be closed first

原文地址: https://www.cveoy.top/t/topic/hq1a 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录