SqlDataReader.GetXmlReader(int) returns unusable reader rather than throwing on DBNull
- Dominant language
- C#
- Stars
- 989
- Forks
- 340
- Avg merge
- 4d 18h
- Merged PRs (30d)
- 69
Description
### 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.
```C#
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
Contributor guide
Assessment
This issue has not been assessed yet.