I’ve come up with a simple example that hopefully illustrates my goal. I currently have a method that returns a kind of sort “ranking” its not that complicated but it doesn’t translate to SQL. The performance is awful because it is all done in memory and I’m trying to improve the speed.
public class Something
{
DateTime Date {get; set;}
// ...
public int SortRank(Sort sort)
{
if (sort == Sort.Newest)
{
return -Date.Ticks;
{
else if (sort == sort.Oldest)
{
return Date.Ticks;
}
}
}
enum Sort
{
Newest,
Oldest
}
using (Context db = new Context()
{
var q = db.GetTable<Something>()
.OrderBy(x=> x.SortRank(Sort.Newest));
}
SortRank() currently has no translation to SQL so I’d like to convert it to an Expression so that it can be evaluated in the database. What is the best way to do this? And yes I know I could just implement this inline within the anonymous lambda but I’m more interested in how to generate an Expression.
I would suggest as others have suggesting that you create an IOrderedQueryable. Creating an expression (especially one like you have above) is pretty easy. You can look at the parameter for OrderBy to get an idea of how to construct it and it would look something like:
Then you can use it like this
db.GetTable<Something>().OrderBy(sortExpression). So you can see how you can create different sort expressions fairly easily. That said I still think something where you are creating an IOrderedQueryable is the cleanest and will produce the best SQL query.you could even change the signature to
and use it as an extension method.
Then you can call it like this:
The other option is to create Expression Trees that translate your enum directly to a query however that is more complicated and I am sure you can find some great information on those on Google and SO.