How does nesting an OrderBy in a Dynamic Linq query work?
我正在使用动态LINQ,今天我想构建一个稍微复杂一点的嵌套查询:
1 2 3 4 5 | "Composition .Where(((ExpirationDate > DateTime.UtcNow.Date) && (ExpirationDate.Year != 9999))) .OrderBy("ExpirationDate ASC") .Select(ExpirationDate) .FirstOrDefault() == @0" |
(在这篇文章中,分隔符只是为了可读性,而不是真正的代码)
查询由字符串变量持有并传递给:
1 2 3 4 | private static Func<IQueryable<T>, object, IQueryable<T>> CreateWhereExpression<T>(string whereClause) where T : class { return (q, o) => q.Where(whereClause, o); } |
它很高兴地创建了where表达式。(请注意,WHERE子句包含"composition.where…."上方的确切字符串)但一旦到了执行的时候,它就会抱怨:
No applicable aggregate method 'OrderBy' exists
所以我的问题是,我做错了什么?如何使嵌套的orderby工作?
默认情况下,dynamicLinq支持对
1 2 3 4 5 6 7 | interface IEnumerableSignatures { .... void OrderBy(object selector); void Select(object selector); void FirstOrDefault(); } |
在那之后,你需要像这样修复
1 2 3 4 5 6 7 8 | 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 ) .... } |
最后,下一个查询将起作用
1 2 3 4 5 | "Composition .Where((ExpirationDate > DateTime.UtcNow.Date) && (ExpirationDate.Year != 9999)) .OrderBy(ExpirationDate) .Select(ExpirationDate) .FirstOrDefault() == @0" |