Skip to content

SqlDataReader.GetFieldValueAsync<T> throws InvalidCastException for nullable columns #17

@priyankatiwari08

Description

@priyankatiwari08

Describe the bug

When calling SqlDataReader.GetFieldValueAsync<int?>() on a nullable int column that contains a non-null value, an InvalidCastException is thrown. The synchronous GetFieldValue<int?>() works correctly.

To reproduce

using var connection = new SqlConnection(connectionString);
await connection.OpenAsync();

using var command = new SqlCommand("SELECT CAST(42 AS int) AS Value", connection);
using var reader = await command.ExecuteReaderAsync();
await reader.ReadAsync();

// This works fine
var syncValue = reader.GetFieldValue<int?>(0); // returns 42

// This throws InvalidCastException
var asyncValue = await reader.GetFieldValueAsync<int?>(0); // throws!

Expected behavior

GetFieldValueAsync<int?>() should return the value (42) just like the synchronous version.

Actual behavior

System.InvalidCastException: Unable to cast object of type 'System.Int32' to type 'System.Nullable`1[System.Int32]'.
   at Microsoft.Data.SqlClient.SqlDataReader.GetFieldValueAsync[T](Int32 ordinal, CancellationToken cancellationToken)

Further technical details

Microsoft.Data.SqlClient version: 6.0.0-preview3
Target framework: .NET 8.0
SQL Server version: Azure SQL Database
Operating system: Windows 11

The issue seems to be in the async code path where the type conversion doesn't handle Nullable<T> unwrapping like the sync path does.

Metadata

Metadata

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions