我正在尝试为Linq to Entities编写自定义的OrderBy扩展方法,其中我可以根据参数对ASC或DESC进行排序。我的第一次尝试如下:Linq to Entities - 自定义方法(OrderBy)在lambda语句中失败
public static class LinqExtensions
{
public static IOrderedQueryable<TSource> OrderByExtension<TSource, TKey>(this IQueryable<TSource> source, Expression<Func<TSource, TKey>> keySelector, bool isDescending = true)
{
return (isDescending) ? source.OrderByDescending(keySelector) : source.OrderBy(keySelector);
}
}
这很好用......只要我不在lambda表达式中使用这个方法。玩具的例子是:
using (var dbContext = new FooDBEntities())
{
var foo = dbContext.Fubars.SelectMany(x => dbContext.Fubars.OrderByExtension(y => y.Foo, true)).ToList();
}
当我运行上面的代码程序吹灭,我得到以下错误:
Unhandled Exception: System.NotSupportedException: LINQ to Entities does not recognize the method 'System.Linq.IOrderedQueryable`1[ExpressionTreeFoo.Fubar] OrderByExtension[Fubar,String](System.Linq.IQueryable`1[ExpressionTreeFoo.Fubar], System.Linq.Expressions.Expression`1[System.Func`2[ExpressionTreeFoo.Fubar,System.String]], Boolean)' method, and this method cannot be translated into a store expression.
错误几乎说明了一切。该框架不知道如何将我的自定义扩展方法转换为SQL可以理解的东西。
我一直在做一些谷歌搜索,但我没有看到任何明确表示这是或不可能的东西。所以我的问题是..有什么办法可以在一个lambda表达式中工作的自定义OrderBy方法(扩展方法或不)?
你确定它与简单的查询完全正常:一个完整的描述,可以发现?你检查了生成的SQL吗? –
是的,我已验证。我正在使用:context.Database.Log = s => System.Diagnostics.Debug.WriteLine(s)来打印查询。 – Soto