The exception is suggesting that the problem is related to performing the operation rather than an issue with converting the types involved. Using LOG10
in SQL will throw this exception when passed a negative number (try it: SELECT LOG10(-1)
). If SqlFunctions.DateDiff
returns a negative number (which it can, depending on the Created
date), your query will fail.
I'm guessing you just need to switch DateTime.Today
and v.Created
to get this working with appropriate casting like so:
this.Queryable
.Select(v => v.UpVote +
SqlFunctions.Log10(
(double?)SqlFunctions.DateDiff("d", v.Created, DateTime.Today));
Or if v.Created
happens to include future dates or there's some negative time differences you can use Math.Abs
to ensure it's always positive like so:
this.Queryable
.Select(v => v.UpVote +
SqlFunctions.Log10(
(double?)Math.Abs(
SqlFunctions.DateDiff("d", DateTime.Today, v.Created)));
Edit - In addition to failing with negative numbers, LOG10
will fail when 0 is provided. You can filter out 0, or ignore it as a modifier:
from v in this.Queryable
let dayDiff = SqlFunctions.DateDiff("d", v.Created, DateTime.Today)
let voteWeight = dayDiff == 0 ?
0 :
SqlFunctions.Log10((double?)dayDiff)
select v.UpVote + voteWeight
Didn't test this exact query out, but the jist of it is that numbers less than or equal to 0 need to be handled somehow.