bit*_*bit 5 c# linq azure-cosmosdb azure-cosmosdb-sqlapi
我试图.Any()在子句中嵌套一个.Where()子句来查询本地 CosmosDb 模拟器。
代码如下所示;其中permittedStundentIds是变量 ( List<long>) 且是CosmosDb 中的aaDocument
.Where(a => permittedStudentIds.Any(sId => a.Students.Any(s => s.Id == sId)));
Run Code Online (Sandbox Code Playgroud)
当我执行查询时,出现错误:
不支持“任意”方法。ActivityId:800000a8-0002-d600-b63f-84710c7967bb,文档db-dotnet-sdk/1.22.0主机/64位MicrosoftWindowsNT/10.0.16299.0
我尝试了多种变体来获得等效的表达式,但无济于事。唯一有效的方法是使用 a.Contains()并对学生索引进行硬编码;这是不可行的,因为学生的人数可能不知道。
.Where(a => permittedStudentIds.Contains(a.Students[0].Id));
Run Code Online (Sandbox Code Playgroud)
我确实了解 CosmosDb 的 Sql API 尚不支持某些 lambda 扩展,但是有解决方法吗?
在尝试了各种 lambda 表达式的多种组合之后,以下是对我有用的结果。
我StudentIds向我的DocumentModel班级添加了一个属性;冗余但单独用于过滤。
此后,我OR-ed使用 进行查询.Contains(),如下所示:
Expression<Func<MyDocumentModel, bool>> query = a => a.StudentIds.Contains(permittedStudentIds[0]);
foreach (var id in permittedStudentIds.Skip(1))
{
query = query.Or(a => a.StudentIds.Contains(id));
}
Run Code Online (Sandbox Code Playgroud)
然后使用如下查询:
.Where(query);
Run Code Online (Sandbox Code Playgroud)
对于这query.Or()部分,我使用了以下类:
// See: https://blogs.msdn.microsoft.com/meek/2008/05/02/linq-to-entities-combining-predicates/
public static class ExpressionExtensions
{
public static Expression<T> Compose<T>(this Expression<T> first, Expression<T> second, Func<Expression, Expression, Expression> merge)
{
// build parameter map (from parameters of second to parameters of first)
var map = first.Parameters.Select((f, i) => new { f, s = second.Parameters[i] }).ToDictionary(p => p.s, p => p.f);
// replace parameters in the second lambda expression with parameters from the first
var secondBody = ParameterVistor.ReplaceParameters(map, second.Body);
// apply composition of lambda expression bodies to parameters from the first expression
return Expression.Lambda<T>(merge(first.Body, secondBody), first.Parameters);
}
public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> first, Expression<Func<T, bool>> second)
{
return first.Compose(second, Expression.AndAlso);
}
public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> first, Expression<Func<T, bool>> second)
{
return first.Compose(second, Expression.OrElse);
}
}
public class ParameterVistor : ExpressionVisitor
{
private readonly Dictionary<ParameterExpression, ParameterExpression> map;
public ParameterVistor(Dictionary<ParameterExpression, ParameterExpression> map)
{
this.map = map ?? new Dictionary<ParameterExpression, ParameterExpression>();
}
public static Expression ReplaceParameters(Dictionary<ParameterExpression, ParameterExpression> map, Expression exp)
{
return new ParameterVistor(map).Visit(exp);
}
protected override Expression VisitParameter(ParameterExpression p)
{
ParameterExpression replacement;
if (map.TryGetValue(p, out replacement))
{
p = replacement;
}
return base.VisitParameter(p);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5349 次 |
| 最近记录: |