gpt4 book ai didi

linq - 如何使 EF-Core (2.1) 编译查询返回 IQueryable?

转载 作者:行者123 更新时间:2023-12-02 06:47:40 25 4
gpt4 key购买 nike

我一直在尝试将在我的应用程序中经常执行的查询转换为已编译的查询,但没有成功。我将其归结为一个简单的查询,因此得出的结论是我一定误解了某些东西的工作原理。

这是不使用编译查询的简单示例查询(可行):

private static Func<Entities, int, string, IQueryable<Users>> _getUsers =
(Entities context) =>
from au in context.Users select au;

一旦我添加了编译查询调用:

private static Func<Entities, int, string, IQueryable<Users>> _getUsers =
EF.CompileQuery((Entities context) =>
from au in context.Users select au);

我得到了这个异常(exception):

Cannot implicitly convert type 'System.Func>' to 'System.Func>'. An explicit conversion exists (are you missing a cast?)

对于我的一生,我无法弄清楚我做错了什么......有什么建议吗?

最佳答案

How do I make an EF-Core (2.1) Compiled Query return an IQueryable?

你不能。全部 EF.Compile方法返回 IEnumerable<TResult>TResult ,以及对应的 Async方法分别返回 AsyncEnumerable<TResult>Task<TResult> .

如您所见,没有IQueryable<T>返回方法。换句话说,编译后的查询应该是最终的(不可组合的) - 重载允许您传递必要的参数。

我不能确切地说这是为什么。 Explicitly Compiled Queries 的解释在 EF Core 文档中是:

Although in general EF Core can automatically compile and cache queries based on a hashed representation of the query expressions, this mechanism can be used to obtain a small performance gain by bypassing the computation of the hash and the cache lookup, allowing the application to use an already compiled query through the invocation of a delegate.

看起来这个想法不仅仅是缓存 IQueryable表达式树,但也跳过表达式树到它们内部使用的任何数据结构的转换。

关于linq - 如何使 EF-Core (2.1) 编译查询返回 IQueryable?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53484492/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com