Исходя из этого вопроса, я снова и снова пишу следующий код:
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
}
}
}
Довольно утомительно вкладывать два оператора использования. Есть ли способ сообщить SqlDataReader, что он владеет командой, и сообщить команде, что он владеет соединением?
Если бы был способ сделать это, я мог бы написать вспомогательный метод, который можно было бы вызвать так:
// 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
}
Или я должен прикусить пулю и написать свою собственную обертку поверх SqlDataReader?