Linq to entities 中带有 SwitchExpression 的 OrderBy

OrderBy with SwitchExpression in Linq to entities

我需要为枚举定制 orderby。我尝试使用 SwitchExpression:

public static IQueryable<T> MyOrderByEnum<T>(this IQueryable<T> source, string propName, Type enumType)
    {
        var type = typeof (T);
        var property = type.GetProperty(propName);
        var parameter = Expression.Parameter(type, "p");
        var propertyAccess = Expression.Property(parameter, property);

        var enumValues = Enum.GetValues(enumType);
        var switchCases = new SwitchCase[enumValues.Length];
        int i = 0;
        foreach (var val in enumValues)
        {
            switchCases[i] = Expression.SwitchCase(
                Expression.Constant(val.ToDisplay()),
                Expression.Constant(val)
                );
            i++;
        }

        var switchExpr1 =
            Expression.Switch(
                propertyAccess,
                Expression.Constant(""),
                switchCases
                );

        var orderByExp1 = Expression.Lambda(switchExpr1, parameter);
        MethodCallExpression resultExp = Expression.Call(typeof (Queryable), "OrderBy", new[] {type, orderByExp1.Body.Type}, source.Expression, orderByExp1);
        return (IOrderedQueryable<T>) source.Provider.CreateQuery(resultExp);
    }

但是当我执行

filtered.MyOrderBy("field1", typeof(FieldState)).ToList();

我收到错误:

Unknown LINQ expression of type 'Switch'.

是否有另一种方法来制作将转化为 sql 构造 "CASE WHEN ..." 的顺序表达式?

尝试Expression.Condition (https://msdn.microsoft.com/en-us/library/bb340500%28v=vs.110%29.aspx) 我认为这转化为 CASE When if used in an anonymous projection