mercredi 28 mars 2018

EF Order by Nullable DateTime using string and nested reflection

According to this question I have created my methods for ordering data sets.

public static IOrderedQueryable<T> Order<T>(this IQueryable<T> source, string propertyName,
    ListSortDirection direction = ListSortDirection.Ascending)
{
    return ListSortDirection.Ascending == direction
        ? source.OrderBy(ToLambda<T>(propertyName))
        : source.OrderByDescending(ToLambda<T>(propertyName));
}

private static Expression<Func<T, object>> ToLambda<T>(string propertyName)
{
    var propertyNames = propertyName.Split('.');
    var parameter = Expression.Parameter(typeof(T));
    var body = propertyNames.Aggregate<string, Expression>(parameter, Expression.Property);

    return Expression.Lambda<Func<T, object>>(Expression.Convert(body, typeof(object)), parameter);
//            return Expression.Lambda<Func<T, object>>(body, parameter);
}

It was fine until I have tried to use it with Nullable<DateTime>, I have called Expression.Convert to box the Nullable<DateTime> to object and it would have worked if it wasn't Nullable, but unfortunately it throws

Unable to cast the type 'System.Nullable`1[[System.DateTime, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]' to type 'System.Object'. LINQ to Entities only supports casting EDM primitive or enumeration types.

It is understandable for me that EF cannot handle this Nullable object according to this anwser.
But I don't know how to manipulate this expression to get what I want, which in this case is to replace null date to DateTime.MaxValue.





Aucun commentaire:

Enregistrer un commentaire