Search code examples
c#datareaderdbconnection

How does DataReader (DbCommand) handle DB communication?


In a software which I'm trying to understand, the DataReader class is received from a IDbCommand-type (inherited) via ExecuteReader().

I'm pretty new to C# and database communication, so: How does DataReader handle the communication with a database?

  • Does it receive the entire response from the query when performing ExecuteReader(), and then the response is stepped through locally with reader.Read()?
  • Or does each reader.Read() call get the next item from the database over the network?
  • Or, something else which I've not thought of?

Solution

  • Technically, "it depends", because DbDataReader is an abstract class that can be implemented any way you see fit -- including buffering the whole result.

    Practically, though, the interface is geared towards piecemeal reading, and so are the implementations. If we take SqlDataReader as the example, the initial call to .ExecuteReader() will start processing of the command and will cause the server to offer results, then each call to .Read() will fetch a row over the network. However, not every call to .Read() necessarily involves network traffic, as multiple rows might be bundled in a packet so the read can be satisfied from a buffer.

    The same applies to columns, even -- they may span network packets or even contain streams, so all the .GetX() methods potentially involve an additional network roundtrip (which is why all of them also have Async versions in .NET 4.5 and higher).