This question is locked. New answers and comments are not allowed.
Speaking in Northwind terms consider the following LINQ query:
Quite simple, isn't it? This results in approximately the followinf query:
See the problem? You're doing an optimization that can only be done if the two tables with Any() are the same. Which is not the case here. If I'm really fortunate the columns referenced in table#2 do not exist in table#1 and I get an exception. If I'm not I get wrong data!
The same query generates semantically correct SQL if I replace || with && but again it makes some tweaking that has no performance gain in most cases and even worse performance depending on the complexity of the Any() predicate:
This is the SQL I would expect, almost literally the same as the LINQ query:
Using OpenAccess 2013.2.702.
var q = from c in db.Categories where db.Products.Any(p => p.CategoryID == c.CategoryID) || db.Suppliers.Any(s => s.CompanyName == c.CategoryName) select c.CategoryID;Quite simple, isn't it? This results in approximately the followinf query:
SELECT c.[CategoryID] AS COL1FROM [Categories] cWHERE EXISTS( SELECT p.[ProductID] FROM [Products] p WHERE (p.[CategoryID] = c.[CategoryID] OR p.[CompanyName] = c.[CategoryName]))See the problem? You're doing an optimization that can only be done if the two tables with Any() are the same. Which is not the case here. If I'm really fortunate the columns referenced in table#2 do not exist in table#1 and I get an exception. If I'm not I get wrong data!
The same query generates semantically correct SQL if I replace || with && but again it makes some tweaking that has no performance gain in most cases and even worse performance depending on the complexity of the Any() predicate:
SELECT c.[CategoryID] AS COL1FROM [Categories] cWHERE EXISTS( SELECT p.[ProductID] FROM [Products] p WHERE p.[CategoryID] = c.[CategoryID] AND EXISTS ( SELECT s.[SupplierID] FROM [Suppliers] s WHERE s.[CompanyName] = 'AAA' )) This is the SQL I would expect, almost literally the same as the LINQ query:
SELECT c.[CategoryID] AS COL1FROM [Categories] cWHERE EXISTS( SELECT p.[ProductID] FROM [Products] p WHERE p.[CategoryID] = c.[CategoryID]) {AND|OR} EXISTS( SELECT s.[SupplierID] FROM [Suppliers] s WHERE s.[CompanyName] = c.[CategoryName])