Wednesday, August 24, 2011

Cast Error on SqlDataReader using Enterprise Data Library 5.0

I was trying to fill the dropdown in the conventional way by binding the dropdown with the DataReader. But, somehow couldn't do it and was getting the cast error.

After some googling, got this article which I thought worth sharing it with others -

ExecuteReader in Enterprise Library wraps IDataReader into RefCountingDataReader that as SqlDataReader implements IDataReader interface.
RefCountingDataReader has InnerReader property that you can cast to SqlDataReader.


Here is the code -

SqlDataReader reader;
reader = ((RefCountingDataReader)db.ExecuteReader(command)).InnerReader as SqlDataReader;
if (reader != null)
reader.Read();
return reader;