From d924e3da0e5cbdb148d64236d14f0f45694cb413 Mon Sep 17 00:00:00 2001 From: Andrea Canciani Date: Sat, 22 Jun 2024 14:19:29 +0200 Subject: [PATCH] Fix bool comparison on SqlServer The provider for SqlServer is currently unable to translate `bool?` expressions when they are on Boolean values instead of `BIT`s. Work around this by performing the usual translation. --- .../Query/Internal/SqlServerSqlNullabilityProcessor.cs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/EFCore.SqlServer/Query/Internal/SqlServerSqlNullabilityProcessor.cs b/src/EFCore.SqlServer/Query/Internal/SqlServerSqlNullabilityProcessor.cs index d58168196aa..255c3f460a7 100644 --- a/src/EFCore.SqlServer/Query/Internal/SqlServerSqlNullabilityProcessor.cs +++ b/src/EFCore.SqlServer/Query/Internal/SqlServerSqlNullabilityProcessor.cs @@ -118,6 +118,7 @@ protected override SqlExpression RewriteNullSemantics( var result = base.RewriteNullSemantics(sqlBinaryExpression, left, right, leftNullable, rightNullable, optimize, out nullable); if (_useIs + && IsSupportedSubExpression(left, leftNullable) && IsSupportedSubExpression(right, rightNullable) && sqlBinaryExpression.OperatorType is ExpressionType.Equal or ExpressionType.NotEqual && result is SqlBinaryExpression { OperatorType: ExpressionType.AndAlso or ExpressionType.OrElse }) { @@ -131,6 +132,14 @@ protected override SqlExpression RewriteNullSemantics( } return result; + + // The provider for SqlServer is unable to translate `bool?` expressions + // when they are on Boolean values instead of `BIT`s. See #34001 + static bool IsSupportedSubExpression(SqlExpression sqlExpression, bool nullable) => + !nullable + || sqlExpression.Type != typeof(bool) + || (sqlExpression is not SqlUnaryExpression { OperatorType: ExpressionType.Not } or + SqlBinaryExpression { OperatorType: ExpressionType.AndAlso or ExpressionType.OrElse }); } ///