Grouping in condition is being dropped
Asked Answered
T

2

6

LINQ to NHibernate removes parenthesis in where clause:

session.Query<MyEntity>().Where(x => (x.MyProp1 < end && x.MyProp1 > start) ||
                                     (x.MyProp2 < end && x.MyProp2 > start));

This results in the following query (note the missing parenthesis):

select <columns> from MY_ENTITY where MY_PROP1 < :p0 and MY_PROP1 > :p1 or 
                                      MY_PROP2 < :p2 and MY_PROP2 > :p3;

This is a huge problem, because it changes the query condition significantly.

Is this a known problem or am I doing something wrong?

Ticktack answered 15/2, 2012 at 16:30 Comment(3)
Hmm, that seems like you've found a bug, you could split the query into two and later on merge them, but still this should workFertility
Does the query not actually execute properly when run? I can't be sure, but it's possible that due to the order of operations the parenthesis aren't required. This is at least feasible.Guzman
@Servy: You nailed it. AND takes precedence over OR. Please post it as an answer so I can accept it.Ticktack
G
5

Because AND has a higher precedence in order of operations over OR the parenthesis are not needed, so the query provider doesn't add in the redundant information.

To help remember orders of operations, a boolean AND is considered analogous to multiplication (on a binary value) and OR is considered analogous to addition on binary values. When dealing with boolean algebra (in a non-programming environment) it is actually not uncommon to use * for AND and + for OR.

Guzman answered 15/2, 2012 at 17:56 Comment(1)
+1 for the explanation of why AND comes first. I studied boolean algebra about 15 years ago and I had forgot completely about the operator equivalence.Chuvash
C
1

AND has higher precedence than OR, just like multiplication has higher precedence than addition.

Therefore, the parentheses are redundant and do not exist in the expression tree.

Chuvash answered 15/2, 2012 at 17:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.