Skip to content

Fix InvalidCastException in DataTable.Select() with OR operator on SqlBoolean columns#127912

Open
pumpkin-bit wants to merge 1 commit intodotnet:mainfrom
pumpkin-bit:fix/datatable-select-or-sqlboolean-or
Open

Fix InvalidCastException in DataTable.Select() with OR operator on SqlBoolean columns#127912
pumpkin-bit wants to merge 1 commit intodotnet:mainfrom
pumpkin-bit:fix/datatable-select-or-sqlboolean-or

Conversation

@pumpkin-bit
Copy link
Copy Markdown
Contributor

Problem/Bug

DataTable.Select() throws InvalidCastException when using the OR operator when columns are of type SqlBoolean.

table.Columns.Add("Col1", typeof(SqlBoolean));
table.Columns.Add("Col2", typeof(SqlBoolean));
table.Select("Col1 OR Col2"); // InvalidCastException

In BinaryNode.EvalBinaryOp, the Operators.Or branch casts (bool)vLeft when the column is of type SqlBoolean the Eval() method returns a boxed SqlBoolean, not a bool. CLR unboxing requires exact type matching. Casting a boxed SqlBoolean to bool results in an InvalidCastException.

The AND operator is implemented correctly nearby it has separate branches: if (vLeft is bool) ... else { ((SqlBoolean)vLeft).IsFalse }. The OR branch was simply forgotten to be updated in the same way as AND.


Solution

Replaced the unconditional (bool)vLeft with a type check with two branches, mirroring the AND logic

I've also attached a test that confirms my hypothesis. BEFORE my fixes, it throws the following crash:

System.InvalidCastException: Unable to cast object of type 'System.Data.SqlTypes.SqlBoolean' to type 'System.Boolean'.

AFTER my fixes:

  Discovering: System.Data.Common.Tests (method display = ClassAndMethod, method display options = None)
  Discovered:  System.Data.Common.Tests (found 2 of 1833 test cases)
  Starting:    System.Data.Common.Tests (parallel test collections = on [6 threads], stop on fail = off)
  Finished:    System.Data.Common.Tests
=== TEST EXECUTION SUMMARY ===
   System.Data.Common.Tests  Total: 5, Errors: 0, Failed: 0, Skipped: 0, Time: 8.108s

@dotnet-policy-service dotnet-policy-service Bot added the community-contribution Indicates that the PR has been added by a community member label May 7, 2026
@dotnet-policy-service
Copy link
Copy Markdown
Contributor

Tagging subscribers to this area: @SamMonoRT, @dotnet/efteam
See info in area-owners.md if you want to be subscribed.

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

Labels

area-System.Data community-contribution Indicates that the PR has been added by a community member

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant