它似乎返回 IEnumerable 而不是 IQueryable:
方法参数:Func<Cat, bool> predicate
代码:
var allCats = _catEntities.GetCats(); // IQueryable
if (skip.HasValue) allCats = allCats .Skip(skip.Value);
if (take.HasValue) allCats = allCats .Take(take.Value);
if (predicate != null)
{
allCats = allCats.Where(predicate);
}
这不会编译,因为 .Where
返回 IEnumerable
而不是 IQueryable
.我知道我能做到 .AsQueryable
或其他但我怀疑不会将其视为适当的 IQueryable
.
有没有简单的解决方法?
最佳答案
问题是 Func<Cat, bool>
已编译为 .NET 代码,因此无法在 .NET 进程之外执行。
因此,为了将谓词应用于 allCats
,由 allCats
定义的查询到时候就得执行了。使用 AsQueryable
正如您所猜测的那样,只会包装返回的 IEnumerable
枚举。
如果您希望谓词由 LINQ 提供程序翻译和执行,您可以使用 Expression<Func<Cat, bool>>
.请注意,这将在 IQueryable
之间引入耦合。谓词的实现和定义。 (因为谓词必须是 LINQ 提供程序可以执行的内容)。
使用 lambda 表达式,可以定义 Expression<Func<Cat, bool>>
很简单:
Expression<Func<Cat, bool>> predicateExpression = c => c.Gender == Gender.Male;
关于c# - 当您应用谓词时,是否可以从 EF 集中取回 IQueryable<>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26233130/