如何在动态Linq查询中嵌套OrderBy? [英] How does nesting an OrderBy in a Dynamic Linq query work?

查看:70
本文介绍了如何在动态Linq查询中嵌套OrderBy?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Dynamic Linq,今天我想构建一个稍微复杂一点的嵌套查询:

I'm using Dynamic Linq and today I wanted to build a slightly more complex nested query:

"Composition
.Where(((ExpirationDate > DateTime.UtcNow.Date) && (ExpirationDate.Year != 9999)))
.OrderBy(\"ExpirationDate ASC\")
.Select(ExpirationDate)
.FirstOrDefault() == @0"

(这些中断只是为了便于阅读,而在代码中并未真正存在)

(the breaks are only there for readability in this post, not really there in code)

查询由字符串变量保存,并传递给此变量:

The query is held by a string variable and passed to this:

private static Func<IQueryable<T>, object, IQueryable<T>> CreateWhereExpression<T>(string whereClause) where T : class
{
     return (q, o) => q.Where(whereClause, o);
}

愉快地创建Where表达式. (请注意whereClause包含"Composition.Where ...."上方的确切字符串.) 但是一旦执行,它就会抱怨:

Which happily creates the Where expression. (note that whereClause contains the exact string above "Composition.Where....") But as soon as it's time to execute, it will complain:

不存在适用的汇总方法'OrderBy'

No applicable aggregate method 'OrderBy' exists

所以我的问题是,我做错了什么?我如何才能使嵌套的OrderBy正常工作?

So my question is, what am I doing wrong? How can I get the nested OrderBy to work?

推荐答案

默认情况下,DynamicLinq支持对IEnumerable字段进行嵌套查询的一些功能,所有这些功能都在接口IEnumerableSignatures中定义,例如WhereAnyCount等,但没有所需的OrderbySelectFirstOrDefault.
因此,您可以将其添加到

By default DynamicLinq support a little functions for nested query to IEnumerable fields, all it defined in inteface IEnumerableSignatures like Where, Any, Count and etc, but don't have Orderby, Select or FirstOrDefault what you need.
So you can add it to this interface like

interface IEnumerableSignatures
{
    ....
    void OrderBy(object selector);
    void Select(object selector);
    void FirstOrDefault();
}

之后,您需要像这样修复ParseAggregate方法

after that you need fix ParseAggregate method like this

Expression ParseAggregate(Expression instance, Type elementType, string methodName, int errorPos)
{
    ....
    if (signature.Name == "Min" || signature.Name == "Max" 
        || signature.Name == "OrderBy" || signature.Name == "Select" //add this for support OrderBy and Select that need two generic parameters
    )
    ....
}

最后一个下一个查询将起作用

at last next query will be work

"Composition
.Where((ExpirationDate > DateTime.UtcNow.Date) && (ExpirationDate.Year != 9999))
.OrderBy(ExpirationDate)
.Select(ExpirationDate)
.FirstOrDefault() == @0"

这篇关于如何在动态Linq查询中嵌套OrderBy?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆