Tip 6 : Function returning SqlDataReader Type
I am strongly against building a function that returns SqlDataReader type because it destroys the basic purpose of building a function: decoupling or separation of concerns. For SqlDataReader, an active database connection needs be kept open across your function to the client that calls the function.
But, sometimes I have no choice. One of my clients has many DotNetNuke applications that use functions returning SqlDataReader everywhere. I am required to either keep coding style consistent or call functions from their dlls.
So, if you have to work with functions returning SqlDataReader, you need to keep in mind:
1. Within the function, set CommanderBehavior to CloseConnection. It will close the connection automatically when the SqlDataReader is closed.
2. Within the function, never close the connection.
3. In the client code, after completing the data read, close the SqlDataReader.