I want to use some System.Linq
extension methods in a base class whereas derived classes should be able to provide some expressions by overriding specific methods.
Current base class code:
lQuery.OrderBy(s => s.ID) <-- works, *1
I want to replace s => s.ID
by a method call that can be overridden:
... Expression<Func<TSource, TKey>> GetOrderByKey<TSource, TKey>()
{
...
}
But when I override the method like
override Expression<Func<TSource, TKey>> GetOrderByKey<TSource, TKey>()
{
return s => s.ID; <-- compiler error, *2
}
the compiler outputs the error
Cannot implicitly convert type 'int' to 'TKey'
Why is the generic parameter
TKey
magically deduced (and to what?) in line 1 but in line 2 it is deduced to the actual type of the ID property?How to resolve the compiler error?
Thanks in advance.
Edit
I struggle to find the right explanation of the issue. Let's break it down to the following simple lines:
var lQuery = from s in ... select s;
lQuery = lQuery.OrderBy(s => s.ID); // *3
How exactly is that OrderBy
call interpreted by the compiler as it results in an ORDER BY ID ASC
instead of ORDER BY %Value of ID% ASC
? The compiler seems to somehow decide to deduce s.ID
to property name "ID"
instead of taking the actual property data type and thus the int value.
Edit2
Ok, another example for +D Stanley
This works:
void SetOrder<TKey>(IQueryable<%type of s%> aQuery, Expression<Func<%type of s%, TKey>> aKeySelector)
{
aQuery.OrderBy(aKeySelector);
}
...
SetOrder(aQuery, s => s.ID); // <-- works
But this not (the compile error is display as mentioned before)
protected void SetOrder<TKey>(IQueryable<%type of s%> aQuery)
{
Expression<Func<%type of s%, TKey>> lKeySelector = s => s.ID; // <-- deduced to int
aQuery.OrderBy(lKeySelector);
}