I have created a Sql helper class which handles most of my needs.
Amongst those, I have a function which executes a SQL statement and returns a SqlDataReader as follows:
public static SqlDataReader ExecuteCommand(string cmdText, bool useParameters)
{
using (var sqlConnection = new SqlConnection(_connectionString.ConnectionString))
{
sqlConnection.Open();
using (var sqlCommand = new SqlCommand(cmdText, sqlConnection))
{
if (useParameters && SqlParameterCollection.Count > 0)
{
sqlCommand.Parameters.AddRange(SqlParameterCollection.ToArray());
}
using (var sqlDataReader = sqlCommand.ExecuteReader())
{
return sqlDataReader;
}
}
}
}
The problem with this is, obviously, the fact that it returns a sqlDataReader which requires an open connection and the fact that the connection is closed.
I have looked at returning a SqlDataAdapter instead, but after reading the following thread SqlDataAdapter vs SqlDataReader it doesn't sound like such a good idea as a general function to be used in every single scenario when you have absolutely no idea of the amount of data it is supposed to load.
So... What's a good alternative?
The only thing I can think of off the top of my head is to cycle through the rows in the SqlDataReader and do a yield return IEnumerable<IDataRecord>.
Is there any better way of achieving this or is this pretty much it?