Skip to Main Content

OracleDataReader.GetValue() throws InvalidCastException

User_TB37YJul 13 2021 — edited Jul 13 2021

Hello,
I'm using Oracle.ManagedDataAccess.dll in version 4.122.19.1.
I found that in some edge cases, the OracleDataReader throws InvalidCastException when calling GetValue() or GetDecimal(). GetFieldType returns System.Decimal. This behavior seems to be incorrect.
The code below allows to reproduce this problem:

private static void TestAvg(DbConnection connection)
      {
          using (var command = connection.CreateCommand())
          {
              command.CommandText = @"SELECT AVG(VAL) AS AVG
FROM
(
   SELECT CAST(9 AS NUMBER(5, 0)) AS VAL FROM DUAL
   UNION ALL
   SELECT CAST(13 AS NUMBER(5, 0)) AS VAL FROM DUAL
   UNION ALL
   SELECT CAST(1 AS NUMBER(5, 0)) AS VAL FROM DUAL
)";
                  

              using (var reader = command.ExecuteReader())
              {
                  reader.Read();

                  var dataTypeName = reader.GetDataTypeName(0); // Returns "Decimal"
                  Debug.WriteLine(dataTypeName);
                  
                  var fieldType = reader.GetFieldType(0); // Returns Type System.Decimal
                  Debug.WriteLine(fieldType);
                  
                  var isDbNull = reader.IsDBNull(0); // Returns false
                  Debug.WriteLine(isDbNull);
                  
                  var doubleValue = reader.GetDouble(0); // Returns double value successfully
                  Debug.WriteLine(doubleValue);
                  
                  var objectValue = reader.GetValue(0); // Invalid cast exception
                  Debug.WriteLine(objectValue);
                  
                  var decimalValue = reader.GetDecimal(0); // Invalid cast exception
                  Debug.WriteLine(decimalValue);
              }
          }
      }

Checked on the following server versions:
SELECT * FROM v$version
Oracle Database 12c Enterprise Edition Release 12.1.0.2.0 - 64bit Production
Oracle Database 19c Enterprise Edition Release 19.0.0.0.0 - Production

This post has been answered by Alex Keh-Oracle on Jul 16 2021
Jump to Answer
Comments
Post Details
Added on Jul 13 2021
9 comments
404 views