OrderBy在Lambda中带有相关表的动态字符串参数

时间:2017-12-19 16:18:26

标签: c# entity-framework lambda

我有一个扩展orderByField

public static IQueryable<T> OrderByField<T>(this IQueryable<T> q, string 
SortField, bool Ascending){
        var param = Expression.Parameter(typeof(T), "p");
        var prop = Expression.Property(param, SortField);
        var exp = Expression.Lambda(prop, param);
        string method = Ascending ? "OrderBy" : "OrderByDescending";
        Type[] types = new Type[] { q.ElementType, exp.Body.Type };
        var mce = Expression.Call(typeof(Queryable), method, types, 
        q.Expression, exp);
        return q.Provider.CreateQuery<T>(mce);
    }

我用它来传递字符串参数

 string sortBy = "StatusID";
 return dbContext.Requests.OrderByField(sortBy,true)

但我如何使用动态字符串参数orderBy,其中列与请求表相关,如

  dbContext.Requests.OrderBy(x => x.Status.Description)

1 个答案:

答案 0 :(得分:1)

假设您将以SortField的形式收到"Status.Description"参数,您会:

  • 首先必须拆分参数以获取所有属性
  • 迭代属性名称和构建属性访问器表达式
  • 使用构建的表达式作为lambda表达式的主体

例如:

public static IQueryable<T> OrderByField<T>(this IQueryable<T> q, string SortField, bool Ascending)
{
    var param = Expression.Parameter(typeof(T), "p");
    Expression expBody = param;
    string[] props = SortField.Split('.');
    foreach (var prop in props)
    {
        expBody = Expression.Property(expBody, prop);
    }
    var exp = Expression.Lambda(expBody, param);
    string method = Ascending ? "OrderBy" : "OrderByDescending";
    Type[] types = new Type[] { q.ElementType, exp.Body.Type };
    var mce = Expression.Call(typeof(Queryable), method, types, q.Expression, exp);
    return q.Provider.CreateQuery<T>(mce);
}