Saturday, June 14, 2014

Casting an Enterprise Library IDataReader to a SqlDataReader

I recently came upon a project where I had to use ADO.NET once again (rather than Entity Framework) and therefore I naturally reverted to using the Enterprise Library.

Since Enterprise Library v. 6.0 does not support .NET v. 4.0, I was forced to use Enterprise Library v. 5.0.

Of course, I was working with a SQL Server database and encountered an instance where I needed to downcast my IDataReader to a SqlDataReader.

Of course, when I attempted to do a standard cast, I got the following error message:

If I subsequently tried to do a cast using the "as SqlDataReader" indirect cast, I ended up with a NULL SqlDataReader!!

So, obviously, something else was necessary in order to get my code to cast properly.

As luck would have it, this behavior was not documented anywhere in the Enterprise Library documentation nor on MSDN, therefore, I had to do some digging around on the Internet to try and come up with a solution.

Finally, this was the solution that I found that resolved my issue:

public IDataReader ExecuteReader(string sql, params object[] parameterValues)
            RefCountingDataReader refDataReader = (RefCountingDataReader) (db.ExecuteReader(sql, parameterValues));
            SqlDataReader sqlDr = (SqlDataReader) refDataReader.InnerReader;
            return sqlDr;

You can then call it and cast it to the appropriate SqlDataReader wherever it is needed in your code in the following manner:


        public void TestSqlDbReader()
            string customConnString = ConfigurationManager.ConnectionStrings["myConnString"].ConnectionString;
            SqlHelper sqlHelper = new SqlHelper(customConnString);
            using (
                SqlDataReader rdr = sqlHelper.ExecuteReader("get_scheduled_weekdays", new object[] { 1 }) as SqlDataReader)

No comments:

Post a Comment