1

我实现了提供给该方法的动态排序逻辑(请参见此处) 。Expression<Func<T, IComperable>>OrderBy

现在我遇到了问题,EF 无法将IComperablein转换Func<T, IComperable>为其实际类型:

无法将类型“System.Int32”转换为类型“System.IComparable”。LINQ to Entities 仅支持转换 EDM 基元或枚举类型。

System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.ValidateAndAdjustCastTypes(TypeUsage toType,TypeUsage fromType,Type toClrType,Type fromClrType)

有没有办法解决这个问题?

我目前发现的唯一方法是将Func<>'s 作为它们的真实类型“实现”,将此类型保存在旁边Func<>并调用OrderByvia 反射:

public static IQueryable<T> OrderBy<T>(this IQueryable<T> source, Type orderType, object expression)
{
    return typeof(Queryable).GetMethods().First(m => m.Name == "OrderBy")
       .MakeGenericMethod(typeof(T), orderType)
       .Invoke(null, new object[] { source, expression }) as IQueryable<T>
}

但这对我来说似乎很丑陋(而且很慢?),并且不像当前的(遗憾的是仅适用于 LINQ to objects 工作)解决方案那样好用......

更新:
这个问题似乎只在返回intbool在时发生Func<T, IComperable>,因为它适用于string...

4

1 回答 1

1

我现在通过以下方式解决了它:

var orderDelegates = new Dictionary<string, LambdaExpression>();

Expression<Func<Image, int>> id = i => i.Id;
orderDelegates.Add(ContentItem.ORDER_BY_ID, id);
Expression<Func<Image, IComperable>> title = i => i.Title;
orderDelegates.Add(ContentItem.ORDER_BY_Title, title);
//more items...

(我希望这有点短 - 见这里

在我自己的OrderBy

var first = orderDelegates[orderKey ?? defaultKey];
Type firstType = first.GetType().GetGenericArguments()[0].GetGenericArguments()[1];

IOrderedQueryable<T> firstOrder;
if (firstType == typeof(int))
    firstOrder = items.OrderBy<T, int>(first, direction);
else if (firstType == typeof(bool))
    firstOrder = items.OrderBy<T, bool>(first, direction);
else
    firstOrder = items.OrderBy<T, IComparable>(first, direction);

var second = orderDelegates[defaultKey];
Type secondType = second.GetType().GetGenericArguments()[0].GetGenericArguments()[1];
if (secondType == typeof(int))
    return firstOrder.ThenBy<T, int>(second, direction);
else if (secondType == typeof(bool))
    return firstOrder.ThenBy<T, bool>(second, direction);
else
    return firstOrder.ThenBy<T, IComparable>(second, direction);

public static IOrderedQueryable<T> OrderBy<T, K>(this IQueryable<T> items, LambdaExpression expression, OrderDirection? direction)
{
    if (direction == OrderDirection.Ascending || !direction.HasValue)
        return items.OrderBy(expression as Expression<Func<T, K>>);
    else
        return items.OrderByDescending(expression as Expression<Func<T, K>>);
}

public static IQueryable<T> ThenBy<T, K>(this IOrderedQueryable<T> items, LambdaExpression expression, OrderDirection? direction)
{
    if (direction == OrderDirection.Ascending || !direction.HasValue)
        return items.ThenBy(expression as Expression<Func<T, K>>);
    else
        return items.ThenByDescending(expression as Expression<Func<T, K>>);
}
于 2013-08-17T09:13:44.267 回答