Constant Expression in Linq to SQL is not correctly compiled
-
01-07-2021 - |
Question
I have two table (mysql) with master-detail relationship that I want to query in Linq (and then experiment it in LinqPad). The problem is Linq to SQL can't produce the correct result nor SQL statement for the following query
from m in masters
select new {
m.Code,
m.Total,
Value = m.details.Sum(d => d.Qty * d.Price * (1 - 6/100))
}
and another one
from m in masters
select new {
m.Code,
m.Total,
Value = m.details.Sum(d => d.Qty * d.Price * 0.94)
}
the first query will not produce the correct result as the latter, the problem after I check in LinqPad lies within the (1 - 6/100)
that compiled into 1.0
. Can someone explain why?
Solution
The first expression uses integer math and thus is correct, just not what you expected. You've assumed that C# will infer floating point semantics from integer literals. The second expression is a simply a double literal.
In integer math, 6/100
is 0, so (1 - 6/100)
is 1. You need to coerce the division expression into using double values by making the numerator or denominator a double literal.
Instead try:
Value = m.details.Sum(d => d.Qty * d.Price * (1 - 6/100.0))
Note the .0
to make that a double expression.