I am trying to combine the following expressions into a single expression: item => item.sub, sub => sub.key to become item => item.sub.key. I need to do this so that I can create an OrderBy method that translates the element selector separately into a key selector. This can be accomplished using one of the overloads on OrderBy and providing IComparer<T> , but it will not be translated into SQL.
The following is the signature of the method to further clarify what I am trying to achieve, as well as an implementation that does not work, but should illustrate this point.
public static IOrderedQueryable<TEntity> OrderBy<TEntity, TSubEntity, TKey>( this IQueryable<TEntity> source, Expression<Func<TEntity, TSubEntity>> selectItem, Expression<Func<TSubEntity, TKey>> selectKey) where TEntity : class where TSubEntity : class { var parameterItem = Expression.Parameter(typeof(TEntity), "item"); ... some magic ... var selector = Expression.Lambda(magic, parameterItem); return (IOrderedQueryable<TEntity>)source.Provider.CreateQuery( Expression.Call(typeof(Queryable), "OrderBy", new Type[] { source.ElementType, selector.Body.Type }, source.Expression, selector )); }
which will be called as:
.OrderBy(item => item.Sub, sub => sub.Key)
Is it possible? Is there a better way? The reason I want the OrderBy method to work this way is because of the support for the complex key selection expression, which applies to many objects, although they are expanded differently. In addition, I know a way to do this using string representations of deep properties, but I'm trying to keep it strongly typed.
source share