如何根据字符串生成Expression<Func<T, TPaginatedKey>>表达式?

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

我正在实现 Pro Asp.Net Web Api Http Web Services

中所述的通用实体存储库

Asp.Net Tugberk Ugurlu 等人

分页功能如下。请关注第三个参数'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.
}

上面的方法调用如下

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

所以这里第三个参数keySelector的参数是x => x.Id。如您所料,它按 Id 排序,并且硬编码为 Id。现在我想概括一下,以便在 运行 时我应该能够按 Id、ModifiedDate、FirstName 或基于字符串参数(例如 "Id" 或 "ModifiedDate" 或 "FirstName"。那么有人可以问我如何根据字符串生成或创建 Expression<Func<T, TPaginatedKey>> 表达式吗?我想它应该很简单,但我做不到。

我相信您正在寻找的是一个叫做 Expression Trees 的东西,它允许您构建动态表达式。

取自 link 的示例,这是他们通过

进行动态排序的方式
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);