C# Linq to实体中带SwitchExpression的OrderBy
我需要为enum定制orderby。我尝试使用SwitchExpression:C# Linq to实体中带SwitchExpression的OrderBy,c#,linq,linq-to-entities,expression,expression-trees,C#,Linq,Linq To Entities,Expression,Expression Trees,我需要为enum定制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);
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);
}
我得到一个错误:
类型为“Switch”的未知LINQ表达式
是否有另一种方法可以生成将转换为sql构造“CASE-WHEN…”的顺序表达式?尝试表达式。条件()
我认为,如果在匿名投影中使用,则会出现这种情况
filtered.MyOrderBy("field1", typeof(FieldState)).ToList();