Skip to content

SqlDataReader.GetFieldValue<byte[]>() cannot be used to read a native SQL Server JSON column. #4758

Description

@KyMback

Describe the bug

SqlDataReader.GetFieldValue<byte[]>() cannot be used to read a native SQL Server JSON column.

The call throws:

Unhandled exception. System.InvalidCastException: Unable to cast object of type 'System.String' to type 'System.Byte[]'.
   at Microsoft.Data.SqlClient.SqlDataReader.GetFieldValueFromSqlBufferInternal[T](SqlBuffer data, _SqlMetaData metaData, Boolean isAsync)
   at Microsoft.Data.SqlClient.SqlDataReader.GetFieldValueInternal[T](Int32 i, Boolean isAsync)
   at Microsoft.Data.SqlClient.SqlDataReader.GetFieldValue[T](Int32 i)

To reproduce

  1. Create a SQL Server 2025 database with a table containing:

    • Id (UNIQUEIDENTIFIER)
    • JsonCol (JSON)
  2. Insert a row containing valid JSON.

  3. Execute the following code:

#:package Microsoft.Data.SqlClient@7.1.0
#:property PublishAot=false
#:property PublishTrimmed=false

using Microsoft.Data.SqlClient;

var connectionString = "";

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

await using var cmd = connection.CreateCommand();
cmd.CommandText = "SELECT Id, JsonCol FROM Test1";

await using var reader = await cmd.ExecuteReaderAsync();

await reader.ReadAsync();

var id = reader.GetGuid(0);
var json = reader.GetFieldValue<byte[]>(1);

The call to GetFieldValue<byte[]>(1) throws InvalidCastException, because SqlClient appears to have materialized the JSON value as System.String.

Expected behavior

SqlDataReader.GetFieldValue<byte[]>() should support native SQL Server JSON columns and return the JSON payload as UTF-8 bytes.

This appears to be the intended API behavior described in the SqlClient JSON datatype design:

#2622

The design explicitly lists:

SqlDataReader.GetFieldValue<byte[]>(int colOrdinal)

and states that the returned byte[] should be usable by Utf8JsonReader as the high-performance scenario in .NET.

See:

https://learn.microsoft.com/en-us/sql/t-sql/data-types/json-data-type?view=sql-server-ver17
https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-tds/afc7c81b-f931-4ef2-bfeb-d3761072fc4c
https://www.rfc-editor.org/info/rfc8259/

Therefore, an application should be able to consume the JSON payload as UTF-8 bytes without first materializing it as a UTF-16 System.String.

Further technical details

  • Microsoft.Data.SqlClient: 7.1.0
  • .NET SDK/runtime: 10.0.112
  • SQL Server: 2025
  • OS: Windows 11

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions