在LINQ to SQL中替代Any()以获得更好的性能[英] Alternative to Any() in LINQ to SQL for better performance

本文是小编为大家收集整理的关于在LINQ to SQL中替代Any()以获得更好的性能的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

我有一个使用嵌套 .Where() 动态构建的大型查询.我正在使用 Any() 但在性能不佳和一些 SQL 分析之后,我发现 Any() 实际上会导致许多往返并选择相关表的每条记录进行评估,而不是使用 JOIN,例如,这会好得多.

这是表格的表示形式以及正在执行的操作,假设表格 A、B 和 C:

A <-- B --> C

假设我正在查询 A 并且有类似 .Where(a => a.B.C.Any(c => c.IsActive))

的内容

尽管使用 Any() 还有更好的选择吗?

推荐答案

显然,您并没有真正使用 LINQ 将查询远程发送到服务器.看来您使用的是 IEnumerable 查询,而不是 IQueryable 查询.

通常情况下,显示的查询可以转换为 SQL 批发.找出为什么要使用 LINQ to 对象.错误在你身上,而不是在 L2S 身上.(这些错误很容易发生,因为您不能仅仅通过查看代码就可以轻易发现它们).

<块引用>

尽管使用 Any(),还有更好的选择吗?

不知道为什么你认为 Any 是问题所在.它是一个随机的旁观者.

本文地址:https://www.itbaoku.cn/post/1556805.html

问题描述

I have a large query built dynamically with the usage of nested .Where(). I am using Any() but after poor performance and some SQL profiling, I found Any() actually causes many round trips and selects each record of a related table for evaluation instead of using a JOIN, for example, which would be much better.

Here's a representation of the tables and what's being done, assuming tables A, B and C:

A <-- B --> C

Suppose I'm querying A and have something like .Where(a => a.B.C.Any(c => c.IsActive))

Is there a better option in spite of using Any()?

推荐答案

Apparently, you are not really using LINQ to remote your queries to the server. It appears you are using IEnumerable queries, not IQueryable queries.

Normally, the query as shown qould be translated to SQL wholesale. Find out, why you are using LINQ to objects. The bug is with you, not with L2S. (These bugs can easily happen because you cannot trivially spot them just by looking at the code).

Is there a better option in spite of using Any()?

Not sure why you think Any is the problem. It is a random bystander.