Skip to content

SqlDataReader.GetXmlReader(int) returns unusable reader rather than throwing on DBNull #1459

Open
@madelson

Description

@madelson

Describe the bug

Most GetXYZ(int) (e. g. GetInt32, GetString, etc) methods on SqlDataReader will throw if they encounter a DBNull.Value and cannot return it. The exception is GetValue which can just return DBNull.Value directly.

GetXmlReader is another exception but with (in my opinion) less reasonable behavior. When called on a column whose value is SQL NULL, it returns a non-null XmlReader object which fails when read from.

To reproduce

Include a complete code listing (or project/solution) that we can run to reproduce the issue.

var connectionString = "...";
using var conn = new Microsoft.Data.SqlClient.SqlConnection(connectionString);
conn.Open();
using var cmd = conn.CreateCommand();
cmd.CommandText = "select cast(null as xml)";
var reader = cmd.ExecuteReader();
reader.Read();

Console.WriteLine(reader.IsDBNull(0)); // true
using var xmlReader = reader.GetXmlReader(0); // works, does not return null
Console.WriteLine(XDocument.Load(xmlReader)); // throws InvalidOperationException "The XmlReader state should be interactive"
//Console.WriteLine(reader.GetString(0)); // throws SqlNullValueException "Data is Null. This method or property cannot be called on Null values."

Expected behavior

For consistency with the other get methods, I think GetXmlReader should throw SqlNullValueException when called on a DBNull column.

This behavior would be useful when processing query results because any errors due to expected non-null values fail fast early rather than manifesting later as a different-seeming exception.

Further technical details

Microsoft.Data.SqlClient version: 4.0.0
.NET target: .NET 5
SQL Server version: SQL Server 2017
Operating system: Windows 10

Metadata

Metadata

Assignees

No one assigned

    Labels

    Area\DocumentationUse this for issues that requires changes in public documentations/samples.Breaking Change 🔨Issues/PRs that are related with breaking API changes in the driver.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions