【发布时间】:2018-03-24 04:38:28
【问题描述】:
我想使用 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'.
我看到similar question 并在那里回答建议使用.Compile。或者 one more question 构建一个额外的谓词。
所以我尝试使用额外的谓词
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();
所以我想我只是想念一些关于 builder 的东西。
版本更新:我使用的是 dotnet core 2.0 和 LinqKit.Microsoft.EntityFrameworkCore 1.1.10
【问题讨论】:
标签: c# linq .net-core entity-framework-core linqkit