如何使用IN执行linq查询

时间:2014-05-13 09:00:07

标签: linq

我对linq很新,我想做这个查询:

select *
FROm dbo.PremiseProviders p
where p.premiseProviderId IN
  (select a.premiseproviderId
  FROM dbo.PremiseProviderAddresses a, dbo.premiseProviderAddressVersions v
  where a.premiseprovideraddressId = v.premiseprovideraddressId
  and v.postcode = '84280')

但是我不知道怎么做IN部分,第二个Select,有人可以帮忙吗? THX

3 个答案:

答案 0 :(得分:2)

通常将Contains方法转换为IN运算符。例如。你有整数2, 3, 7然后

的集合
   where ids.Contains(p.premiseProviderId)

将被翻译为

   WHERE p.premiseProviderId IN (@p1, @p2, @p3)

但EF非常聪明且与您的查询方法相同

from p in db.PremiseProviders
where (from a in db.PremiseProvideAddresses
       join v in db.PremiseProviderAddressVersions
           on a.premiseprovideraddressId equals v.premiseprovideraddressId
       where v.postcode == "84280"
       select a.premiseproviderId).Contains(p.premiseProviderId)
select p

将被翻译成比你更好的SQL - 它将生成EXISTS子查询。像

这样的东西
SELECT [t0].[premiseProviderId], [t0].[Foo], [t0].[Bar]
FROM [PremiseProviders] AS [t0]
WHERE EXISTS(
    SELECT NULL AS [EMPTY]
    FROM [PremiseProvideAddresses] AS [t1]
    INNER JOIN [PremiseProviderAddressVersions] AS [t2]
       ON [t1].[premiseprovideraddressId] = [t2].[premiseprovideraddressId]
    WHERE [t0].[postcode] = @p1 AND 
          [t1].[premiseproviderId] = [t0].[premiseproviderId]
    )

为了便于阅读,您可以将子查询定义提取到单独的变量中:

var providerIds = 
       from a in db.PremiseProvideAddresses
       join v in db.PremiseProviderAddressVersions
           on a.premiseprovideraddressId equals v.premiseprovideraddressId
       where v.postcode == "84280"
       select a.premiseproviderId;

var providers = from p in db.PremiseProviders
                where providerIds.Contains(p.premiseProviderId)
                select p;

注意:如果不是子查询,您将传递查询执行的结果(即将ID保存到列表或数组,然后生成IN运算符,就像在我的答案中的第一个示例中一样。)

答案 1 :(得分:1)

首先获取给定邮政编码的所有premiseProviderId结果。然后筛选前一个结果中存在PermiseProviderId的提供程序:

var providersIDs = (from a in dbo.PremiseProviderAddresses
                    join v in dbo.premiseProviderAddressVersions
                    on a.premiseprovideraddressId equals v.premiseprovideraddressId
                    where v.postcode == "84280"
                    select a.premiseproviderId).ToList();

var result = dbo.PremiseProviders.Where(x => providersIDs.Contains(x.PremiseProviderId));

答案 2 :(得分:0)

首先为postcode = 84280选择premiseProviderIds(让我们称之为premiseProviderIdsForPostcode84280。

然后你做了类似的事情:

var query = from p in dbo.PremiseProviders
                   where premiseProviderIdsForPostcode84280.Contains(p.premiseProviderId)
                   select p;