Skip to content

Query: Using Or instead of ElseOr, etc. can result in unexpected SQL #7271

Closed

Description

@datasecurity

When I use two conditions joined by an OR, the result is not correct for SQL Server.

How can I fix it?

This is my LINQ code and result in SQL (that reflection created for me):

query.Where(p => ((p.Code == "100000") Or p.Code.EndsWith("200")));
query.Where(p => (p.year == "2015"))}

I added this where clause at runtime, now I add another extension method and it's not working:

query.sum(p => p.value)

Exception:

An exception of type 'System.Data.SqlClient.SqlException' occurred in Microsoft.EntityFrameworkCore.dll but was not handled in user code

Additional information: An expression of non-boolean type specified in a context where a condition is expected, near 'AND'.

SQL translated:

SELECT SUM([e].[Value])
FROM [acc].[Data161] AS [e]
WHERE (CASE
          WHEN RIGHT([e].[Code], LEN(N'201')) = N'201'
             THEN CAST(1 AS BIT) ELSE CAST(0 AS BIT)
       END | 
       CASE
          WHEN RIGHT([e].[Code], LEN(N'199')) = N'199'
             THEN CAST(1 AS BIT) ELSE CAST(0 AS BIT)
       END) 
  AND ([e].[SetadCode] = N'161')

The correct SQL should have = 1 before the AND.

But without sum its works fine and add a = 1 to SQL command

Activity

  1. tuespetre commented on Dec 30, 2016

    @tuespetre
    Contributor

    This turned out not be because of the Sum but because of the interaction between BinaryExpressions and ConditionalExpressions.

  2. added this to the 2.0.0 milestone on Dec 30, 2016
  3. divega commented on Dec 30, 2016

    @divega
    Contributor

    Assigning issue and PR to @smitpatel.

  4. added 5 commits that reference this issue on Feb 4, 2017
    f89471d
    f8a2918
    b2ab380
    98a8049
    1649ad0
  5. liamdawson commented on Feb 14, 2017

    @liamdawson

    Does someone have a workaround for this issue?

  6. smitpatel commented on Feb 14, 2017

    @smitpatel
    Contributor

    Use OrElse instead of Or (Or is bitwise operator, OrElse is logical operator)

  7. liamdawson commented on Feb 14, 2017

    @liamdawson

    Would AndAlso also be the appropriate change for And expressions?

  8. smitpatel commented on Feb 14, 2017

    @smitpatel
    Contributor

    Yes.

  9. changed the title [-]Conditional sum using linq for Or condition[/-] [+]Query: Using Or instead of ElseOr, etc. can result in unexpected SQL[/+] on May 9, 2017
  10. modified the milestones: , 2.0.0 on Oct 15, 2022
  11. added theissue type on Jun 15, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions