我正在尝试使用以下方法:
private static IQueryable<TObject> ApplyOrderBy<TObject, TKey>(IQueryable<TObject> query, OrderByDirection orderByDirection,
Expression<Func<TObject, TKey>> sortExpression, ref bool first)
{
if (orderByDirection == OrderByDirection.None || sortExpression == null) return;
if (orderByDirection != OrderByDirection.Ascending && orderByDirection != OrderByDirection.Descending)
throw new Exception(string.Format("Should never get here! Unknown OrderByDirection enum - '{0}'.", orderByDirection));
if (first)
{
first = false;
query = orderByDirection == OrderByDirection.Ascending
? query.OrderBy(sortExpression)
: query.OrderByDescending(sortExpression);
}
else
{
query = orderByDirection == OrderByDirection.Ascending
? ((IOrderedQueryable<TObject>)query).ThenBy(sortExpression)
: ((IOrderedQueryable<TObject>)query).ThenByDescending(sortExpression);
}
return query;
}
如果你这样称呼它,这个方法很有效:
ApplyOrderByToGet(ref query, OrderByDirection.Ascending, x => x.StartDateTime, ref first);
然后,sort表达式具有强类型DateTime作为类型,LINQ to SQL很高兴。但是,如果要传递具有不同类型的这些表达式的数组,则最终需要一个以“object”作为类型的列表。问题是LINQ to SQL没有弄清楚类型不是对象,而是DateTime。这适用于使用LINQ to对象的常规列表。 看到可以导航表达式树并找出类型是什么,是否可以在调用ApplyOrderBy之前转换/转换表达式?
投射或转换自:
Expression<Func<T, object>>
为:
Expression<Func<T, DateTime>>