I am trying to sort some articles using Linq to Entities. I am using System.Data.Objects.SqlClient.SqlFunctions. This is what I would like to have:
this.Queryable = this.Queryable
.OrderByDescending(v => v.UpVote + SqlFunctions.Log10(
SqlFunctions.DateDiff("d", DateTime.Today, v.Created)));
However, this does not work, since DateDiff returns an int?
and Log10 takes either a double?
or a decimal?
.
I could not find a convert function that does this in SqlFunctions. I tried multiplying it by 1.0, or casting it, but I get the following error:
System.Data.Entity.Core.EntityCommandExecutionException: An error occurred while reading from the store provider's data reader. See the inner exception for details. ---> System.Data.SqlClient.SqlException: An invalid floating point operation occurred.
How do I convert from int?
to double?
or decimal?
using SqlFunctions?
ANSWER:
Based on Ocelot20's response, I switched around the arguments and added a day to the Created day so it never produces a negative or 0 input, which is what caused the error. I also needed to cast UpVote to double. This is what the working version looks like:
var date = DateTime.Today.AddDays(1);
this.Queryable = this.Queryable
.OrderByDescending(v => (double)v.UpVote - SqlFunctions.Log10(Math.Abs((double)
SqlFunctions.DateDiff("d", date, v.Created))));