Search code examples
c#linqlinq-expressions

How to generate Expression<Func<T, TPaginatedKey>> expression based on a string?


I am implimenting Generic Entity Repository as described in Pro Asp.Net Web Api Http Web Services in

Asp.Net Tugberk Ugurlu et al.

The paginated function is as follows. Please focus on the third parameter 'keySelector'

public PaginatedList<T> Paginate<TPaginatedKey>(int pageIndex, int pageSize, Expression<Func<T, TPaginatedKey>> keySelector,
            Expression<Func<T, bool>> predicate, params Expression<Func<T, object>>[] includeProperties)
{
    m_EntitiesContext.Set<T>().OrderBy(keySelector);
    ... // Removed some code here.
}

The above method is called as follows.

m_Repository.Paginate<short>(cmd.Page, cmd.Take, x => x.Id, null);

So here the argument to the third parameter keySelector is x => x.Id. As you can expect, it is ordering by Id, and it is hard coded to Id. Now I want to generalize so that at run time I should be able to order by Id, ModifiedDate, FirstName, or what ever based on a string parameter such as "Id" or "ModifiedDate" or "FirstName". So can someone please how I can generate or create the Expression<Func<T, TPaginatedKey>> expression based on a string? I guess it should be simple enough, but I am unable to do it.


Solution

  • I believe what you are looking for is something called Expression Trees, which allows you to build dynamic expressions.

    Taken from the example from the link, this is how they do a dynamic order by

    MethodCallExpression orderByCallExpression = Expression.Call(
        typeof(Queryable),
        "OrderBy",
        new Type[] { queryableData.ElementType, queryableData.ElementType },
        whereCallExpression,
        Expression.Lambda<Func<string, string>>(pe, new ParameterExpression[] { pe }));
    
    // Create an executable query from the expression tree.
    IQueryable<string> results = queryableData.Provider.CreateQuery<string>(orderByCallExpression);