Following on from this question, I find myself writing the following code over and over again:
SqlCommand command = new SqlCommand();
// Code to initialize command with what we want to do
using (SqlConnection connection = openConnection())
{
command.Connection = connection;
using (SqlDataReader dataReader = thisCommand.ExecuteReader())
{
while (dataReader.Read())
{
// Do stuff with results
}
}
}
It's rather tedious to have to nest the two using statements. Is there a way to tell SqlDataReader that it owns the command, and tell the command that it owns the connection?
If there was a way of doing that then I could write a helper method which could be called like so:
// buildAndExecuteCommand opens the connection, initializes the command
// with the connection and returns the SqlDataReader object. Dispose of the
// SqlDataReader to dispose of all resources that were acquired
using(SqlDataReader reader = buildAndExecuteCommand(...))
{
// Do stuff with reader
}
Or do I have to bite the bullet and write my own wrapper over SqlDataReader?