Moving Data Across Service Boundaries

Yet another question that has come across my inbox more than once in the past week.  Which is a good enough reason to become the topic of a blog.  The question:

"Can a SqlDataReader by return by a web service method?"

The short answer:  No

If you attempt to do so, you will get an InvalidOperationException indicating that the SqlDataReader could not be serialized because it doesn't have a public constructor.  And while that is the technical result, the true reason is slightly different.

The SqlDataReader class is stream based.  That is to say that the connection to the database that feeds the SqlDataReader is kept open and busy for as long as the reader is working with data. If an instance of SqlDataReader were to be returned from a web service method, the client would attempt to do a Read.  Which would use the connection to retrieve data from a database that is no longer around.  And certainly not where the connection expects it to be.  Not a situation that's amenable to success.