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?

Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443
  • 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 work – mfeineis Feb 15 '12 at 16:35
  • 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. – Servy Feb 15 '12 at 16:38
  • 1
    @Servy: You nailed it. [AND takes precedence over OR](http://docs.oracle.com/html/A95915_01/sqopr.htm#i1004611). Please post it as an answer so I can accept it. – Daniel Hilgarth Feb 15 '12 at 17:32

2 Answers2

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.

Servy
  • 202,030
  • 26
  • 332
  • 449
  • +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. – Diego Mijelshon Feb 15 '12 at 18:16
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.

Diego Mijelshon
  • 52,548
  • 16
  • 116
  • 154