Dapper Unable to cast object of type 'Dapper.WrappedReader' to type 'System.Data.SqlClient.SqlDataReader'

c# dapper

Question

Trying to get SqlDataReader using dapper but getting the error on the title. Below is the code:

using (var reader = (SqlDataReader)con.ExecuteReader(query))
                    {
                        while (reader.Read())
                        {
                            //do stuff here with reader
                        } 
                    }

Accepted Answer

As you can see from the source code, WrappedReader is either:

#if DNXCORE50
    internal class WrappedReader : WrappedDataReader

Or:

#else
    internal class WrappedReader : IDataReader, IWrappedDataReader

Both WrappedDataReader and IWrappedReader define a Reader property that will allow you to get the underlying SqlDataReader. Thus try changing your code to:

(SqlDataReader)((IWrappedDataReader)con.ExecuteReader(query)).Reader { ... }

Or:

(SqlDataReader)((WrappedDataReader)con.ExecuteReader(query)).Reader { ... }

That being said, you may want to actually use the original (wrapped) reader for your using clause -- that way it will get an opportunity to react to .Dispose(). If you do it that way, you can get the sql reader in the body of your using clause and use it from then on.



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why