我想使用LinqKit的PredicateBuilder并将谓词传递到相关模型的.Any
方法中。
因此我想要构建一个谓词:
var castCondition = PredicateBuilder.New<CastInfo>(true);
if (movies != null && movies.Length > 0)
{
castCondition = castCondition.And(c => movies.Contains(c.MovieId));
}
if (roleType > 0)
{
castCondition = castCondition.And(c => c.RoleId == roleType);
}
然后使用它来过滤与谓词中的模型相关的模型:
IQueryable<Name> result = _context.Name.AsExpandable().Where(n => n.CastInfo.Any(castCondition));
return await result.OrderBy(n => n.Name1).Take(25).ToListAsync();
但是这会导致一个 System.NotSupportedException: Could not parse expression 'n.CastInfo.Any(Convert(__castCondition_0, Func``2))': The given arguments did not match the expected arguments: Object of type 'System.Linq.Expressions.UnaryExpression' cannot be converted to type 'System.Linq.Expressions.LambdaExpression'.
我看到了类似的问题,那里的答案建议使用.Compile
或者构建额外的谓词。
所以我尝试使用了额外的谓词。
var tp = PredicateBuilder.New<Name>(true);
tp = tp.And(n => n.CastInfo.Any(castCondition.Compile()));
IQueryable<Name> result = _context.Name.AsExpandable().Where(tp);
或者直接使用编译
IQueryable<Name> result = _context.Name.AsExpandable().Where(n => n.CastInfo.Any(castCondition.Compile()));
但我遇到了编译错误:System.NotSupportedException: Could not parse expression 'n.CastInfo.Any(__Compile_0)'
那么,是否有可能将PredicateBuilder的结果转换为可以传递给Any
的形式呢?
注意:我已经成功组合表达式以实现所需的行为,但我不喜欢需要额外的变量。
System.Linq.Expressions.Expression<Func<CastInfo,bool>> castExpression = (c => true);
if (movies != null && movies.Length > 0)
{
castExpression = (c => movies.Contains(c.MovieId));
}
if (roleType > 0)
{
var existingExpression = castExpression;
castExpression = c => existingExpression.Invoke(c) && c.RoleId == roleType;
}
IQueryable<Name> result = _context.Name.AsExpandable().Where(n => n.CastInfo.Any(castExpression.Compile()));
return await result.OrderBy(n => n.Name1).Take(25).ToListAsync();
所以我认为我对构建器有所遗漏。
版本更新: 我使用的是 dotnet core 2.0 和 LinqKit.Microsoft.EntityFrameworkCore 1.1.10
ExpressionStarter
可以转换为Expression
。因此,以下语句有效:var castExpr = (Expression>)castCondition;
context.Name.AsExpandable().Where(n => n.CastInfo.Any(castExpr.Compile())).Count();
由于某种原因,内联变量不起作用。 - IgorExpressionStarter.Compile()
。听起来像是LinqKit工作不完整 :( - Ivan Stoev