开发者

LINQ to Entities integer division incorrect?

开发者 https://www.devze.com 2023-04-10 15:55 出处:网络
I\'m trying to do a little partitioning, dividing list entries into 6-month blocks. Using this LINQ to Entities query, I get results that imply that integer division is not taking place:

I'm trying to do a little partitioning, dividing list entries into 6-month blocks. Using this LINQ to Entities query, I get results that imply that integer division is not taking place:

 from e in enrollments 
let AgeInHalfYears = e.AgeMonths / 6 
select new { e.AgeMonths , 
         AgeInHalfYears, 
         AgeFloor = ((int)AgeInHalfYears) * 6 }

My results are:

AgeMonths   AgeInHalfYears  AgeFloor
68          11              68
41           7              41
34           6              34

I would have expected 66, 36, and 30 in that last column.

I 开发者_Python百科rewrote the LINQ pretty simply as

AgeFloor = e.AgeMonths - (e.AgeMonths % 6)

But I'm still curious about why the division operation is clearly floating point, even with that (int) cast in there... I wouldn't have expected that.


The Entity Framework is probably ignoring your cast when generating the SQL.

LINQ-based SQL generators are rarely (if ever) perfect.
In particular, .Net's type system is different enough from SQL's that they probably ignore all casts.

Try calling Math.Floor instead.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号