我正在尝试使以下方法起作用:
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);
然后,排序表达式具有强类型 DateTime 作为类型,并且 LINQ to SQL 很高兴。但是,如果您想传递这些具有不同类型的表达式的数组,您最终需要一个以“对象”作为类型的列表。问题是 LINQ to SQL 没有弄清楚类型不是对象,而是日期时间。这适用于使用 LINQ to 对象的常规列表。鉴于可以导航表达式树并找出类型是什么,是否可以在调用 ApplyOrderBy 之前转换/转换表达式?
从以下位置投射或转换:
Expression<Func<T, object>>
至:
Expression<Func<T, DateTime>>