Alternative to Any() in LINQ to SQL for better per

2019-07-18 11:00发布

问题:

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()?

回答1:

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.