zulqarnain
zulqarnain

Reputation: 1735

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

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
                        } 
                    }

Upvotes: 3

Views: 1995

Answers (1)

Kirk Woll
Kirk Woll

Reputation: 77536

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.

Upvotes: 7

Related Questions