Thien Vu
Thien Vu

Reputation: 61

OrderBy with a dynamic string parameter in Lambda with related table

I have a extention 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);
    }

I use it for pass string parameter in it

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

But how i can orderBy with a dynamic string parameter with column related with request table like

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

Upvotes: 0

Views: 344

Answers (1)

nejcs
nejcs

Reputation: 1262

Assuming that you would receive SortField argument in the form of "Status.Description", you would:

  • First have to split argument to get all properties
  • Iterate over property names and building property accessor expressions
  • Use built expression as body of lambda expression

For example:

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);
}

Upvotes: 1

Related Questions