When encapsulating the universal SQL Server data accessible method, if the return value type is SqlDataReader, then when creating the connection string, we cannot write the following
public static SqlDataReader ExecuteReader (String strSQL)
{
using (SqlConnection connection = new SqlConnection (connectionString))
{
using (SqlCommand cmd = new SqlCommand (strSQL, connection))
{
Try
{
Connection. Open ();
SqlDataReader myreader = cmd. ExecuteReader (commandbehavior.closeconnection);
return myreader;
}
catch (System.Data.SqlClient.SqlException ex)
{
throw new Exception (ex. Message);
}
}
}
}
When you create a use using a, the SqlConnection will be freed when the SqlDataReader is assigned, and the connection will be closed. While we pass the past SqlDataReader is a reference type that receives a place call passing past SqlDataReader, it will prompt that the connection has been closed and cannot be called because the using (SqlConnection connection = new SqlConnection (connectionString)) at the end of the method, the resource is released, and closed the connection, in order to receive the normal delivery of the past SqlDataReader, when creating the connection can not use using, the correct wording as follows
public static SqlDataReader ExecuteReader (String strSQL)
{
SqlConnection connection = new SqlConnection (connectionString);
using (SqlCommand cmd = new SqlCommand (strSQL, connection))
{
Try
{
Connection. Open ();
SqlDataReader myreader = cmd. ExecuteReader (commandbehavior.closeconnection);
return myreader;
}
catch (System.Data.SqlClient.SqlException ex)
{
throw new Exception (ex. Message);
}
}
}