Skip to content Skip to sidebar Skip to footer

Dynamic Linq Orderby Null Error

I'm using dynamic Linq to order a result set depending on which column is passed in. I'm using this to order a table when a user clicks on a table column. If the property im orderi

Solution 1:

I've found the answer. Replace the OrderBy query in the System.Linq.Dynamic.DynamicQueryable class with the below. It will handle nulls in a property that is an object.

publicstatic IQueryable OrderBy(this IQueryable source, string ordering,
    paramsobject[] values)
{
    //This handles nulls in a complex objectvar orderingSplit = ordering.Split(newchar[] {' '},
        StringSplitOptions.RemoveEmptyEntries);
    var sortField = orderingSplit[0];
    var splitted_sortField = sortField.Split(newchar[] { '.' }, 
        StringSplitOptions.RemoveEmptyEntries);

    if (splitted_sortField.Length > 1)
    {
        sortField = "iif(" + splitted_sortField[0] + "==null,null," + sortField + ")";
    }
    ordering = orderingSplit.Length == 2
       ? sortField + " " + orderingSplit[1]
       : sortField;

    if (source == null) thrownew ArgumentNullException("source");
    if (ordering == null) thrownew ArgumentNullException("ordering");

    ParameterExpression[] parameters = new ParameterExpression[] {
        Expression.Parameter(source.ElementType, "") };
    ExpressionParser parser = new ExpressionParser(parameters, ordering, values);
    IEnumerable<DynamicOrdering> orderings = parser.ParseOrdering();
    Expression queryExpr = source.Expression;
    string methodAsc = "OrderBy";
    string methodDesc = "OrderByDescending";

    foreach (DynamicOrdering o in orderings)
    {
        queryExpr = Expression.Call(
            typeof(Queryable), o.Ascending ? methodAsc : methodDesc,
            new Type[] { source.ElementType, o.Selector.Type },
            queryExpr, Expression.Quote(Expression.Lambda(o.Selector, parameters)));
        methodAsc = "ThenBy";
        methodDesc = "ThenByDescending";
    }
    return source.Provider.CreateQuery(queryExpr);
}

Taken the code from here and baked it directly into the Dynamic Linq function.

Null Reference Exception in a Dynamic LINQ Expression

Post a Comment for "Dynamic Linq Orderby Null Error"