我如何在MongoDB中执行IQueryable请求?

问题描述 投票:2回答:1

我正在尝试连接一些基于IQueryable接口的框架(即OData,如果您想知道的话)。

可以使用以下代码段描述我当前的问题:

var queryable = database.GetCollection<MyItems>("myItems").AsQueryable();
var count1 = queryable.Select(x => x.Order.StateInfo).Count();
// var count2 = queryable.Select(x => x.Order).Select(x => x.StateInfo).Count();

此代码有效,但是如果您取消注释最后一行,则会得到:

System.ArgumentException: Expression of type 'System.Collections.Generic.IEnumerable`1[MyApp.Common.Models.StateInfo]' 
cannot be used for parameter of type 'System.Linq.IQueryable`1[MyApp.Common.Models.StateInfo]' of method
 'Int32 Count[StateInfo](System.Linq.IQueryable`1[MyApp.Common.Models.StateInfo])' (Parameter 'arg0')
   at System.Dynamic.Utils.ExpressionUtils.ValidateOneArgument(MethodBase method, ExpressionType nodeKind, Expression arguments, ParameterInfo pi, String methodParamName, String argumentParamName, Int32 index)
   at System.Linq.Expressions.Expression.Call(MethodInfo method, Expression arg0)
   at System.Linq.Expressions.MethodCallExpression1.Rewrite(Expression instance, IReadOnlyList`1 args)
   at System.Linq.Expressions.ExpressionVisitor.VisitMethodCall(MethodCallExpression node)
   at System.Linq.Expressions.MethodCallExpression.Accept(ExpressionVisitor visitor)
   at MongoDB.Driver.Linq.Processors.Transformer.Visit(Expression node)
   at MongoDB.Driver.Linq.Processors.Transformer.Transform(Expression node)
   at MongoDB.Driver.Linq.MongoQueryProviderImpl`1.Prepare(Expression expression)
   at MongoDB.Driver.Linq.MongoQueryProviderImpl`1.Translate(Expression expression)
   at MongoDB.Driver.Linq.MongoQueryProviderImpl`1.ExecuteAsync[TResult](Expression expression, CancellationToken cancellationToken)
   at MongoDB.Driver.Linq.MongoQueryable.CountAsync[TSource](IMongoQueryable`1 source, CancellationToken cancellationToken)

似乎驱动程序尝试在内存中执行某些操作,从而丢弃了整个IQueryable,因此所有后续调用均失败(例如Select / Where / ...)。带有两个后续SelectSelect/Where对的查询会被中毒,无法在任何地方使用。例如:

var queryable = database.GetCollection<MyItems>("myItems").AsQueryable();
var count1 = queryable.Select(x => x.Order).Where(x => x.StateInfo != null).Count(); 
// System.InvalidOperationException: '{document}.StateInfo is not supported.'

我该怎么办?也许我可以在某个地方举报?

c# mongodb linq mongodb-query iqueryable
1个回答
0
投票

MongoDB C#驱动程序仅部分支持IQueryable,因为用MongoDB聚合管道很难实现所有情况。

因此,如果版本2.10不支持另一个Select中的Select和不支持Where中的Select,我并不感到惊讶。

在当前文档中找不到与此有关的任何信息,但是在v1 doc中是:

选择用于从匹配的文档中投影新的结果类型。投影通常必须是最后一个操作(有一些例外,例如Distinct,Max和Min)。

IQueryable的使用仅限于here所述的基本方法。在here中,您可以找到IQueryable测试,在此我也找不到.Select().Select()

© www.soinside.com 2019 - 2024. All rights reserved.