如何在Linq中的where子句内转换存在条件

时间:2013-09-25 10:23:07

标签: linq

我想在Linq查询中添加以下where子句。如何使用linq下面的子查询

WHERE (Restaurants.[IsActive] = 1) 
AND exists 
(
   select 1 from APIKeys 
   where ApiKey = 'on35e5xbt3m4cbcef4e4448t6wssg11o'
       and (KeyType = 1
       and  fk_RestaurantsID = [t2].[RestaurantsID]
       or KeyType = 2 
       and fk_RestaurantGroupID = RG.RestaurantGroupsID 
       and [t1].[fk_RestaurantsID] in 
           (SELECT RestaurantsID 
            FROM Restaurants 
            WHERE RestaurantGroupsID = RG.RestaurantGroupsID))
)
AND (0 = (COALESCE([t0].[fk_MembersID],0))) 
AND (1 = [t0].[fk_BookingStatusID]) 
AND ([t0].[Email] = 'nike.s@gmail.com') 
AND (([t0].[Phone] = '9999999990') OR ([t0].[MobilePhone] = '9999999990'))

1 个答案:

答案 0 :(得分:0)

使用Any()生成转换为EXISTS的子查询。例如。使用AdventureWorks数据库示例:

from p in Products
where p.FinishedGoodsFlag &&
      SalesOrderDetails.Any(od => od.ProductID == p.ProductID)
select new { p.ProductID, p.Name }

将对数据库产生以下查询:

SELECT [t0].[ProductID], [t0].[Name]
FROM [Production].[Product] AS [t0]
WHERE ([t0].[FinishedGoodsFlag] = 1) AND (EXISTS(
    SELECT NULL AS [EMPTY]
    FROM [Sales].[SalesOrderDetail] AS [t1]
    WHERE [t1].[ProductID] = [t0].[ProductID]
    ))