如何使用 Linq to Entities 从 Same Table 查询 Exists 和 Not Exists

How to Query Exists and Not Exists from Same Table, Using Linq to Entities

我有一个 table,其中包含与这些部分关联的 PartId 和 AccountId 列表。在 table 中,有一个布尔值确定 PartId/AccountId 配对是否是独占俱乐部 (IsInExclusiveClub) 的成员。

我想查询 table 以找到属于专属俱乐部和不属于专属俱乐部的不同 PartId/AccountId 配对。

这是我为此编写的两个 SQL 查询:

加入专属俱乐部:

DECLARE                           @ForeignPassedInKey int; set @ForeignPassedInKey = [Some Integer]

SELECT                     DISTINCT p.PartId
FROM                       dbo.Part p
WHERE                      IsInExclusiveClub = 1
AND                        EXISTS(SELECT * FROM dbo.Parts p2 
                                  WHERE p.partid = p2.partid 
                                  AND p2.Account IN (SELECT AccountId FROM dbo.Accounts
                                                               WHERE ForeignPassedInKey = @ForeignPassedInKey)
                                  AND p2.IsInExclusiveClub = 1)

被排除在专属俱乐部之外:

DECLARE                           @ForeignPassedInKey int; set @ForeignPassedInKey = [Some Integer]

SELECT                     DISTINCT p.PartId
FROM                       dbo.Part p
WHERE                      IsInExclusiveClub = 1
AND                        NOT EXISTS(SELECT * FROM dbo.Parts p2 
                                  WHERE p.partid = p2.partid 
                                  AND p2.Account IN (SELECT AccountId FROM dbo.Accounts
                                                               WHERE ForeignPassedInKey = @ForeignPassedInKey)
                                  AND p2.IsInExclusiveClub = 1)

我将如何使用 Linq to Entities 来编写它。另外,如果您需要更多信息,请告诉我。

这样做可以简化您的查询:

SELECT                  DISTINCT p.PartId
FROM                    dbo.Part p
WHERE                   IsInExclusiveClub = 1
AND                     Account IN (SELECT AccountId FROM dbo.Accounts WHERE ForeignPassedInKey = @ForeignPassedInKey)

对于 NOT EXISTS 查询,您可以将其更改为 "Account NOT IN"。

此 Linq 查询可能如下所示:

var accounts = db.Accounts
                .Where(account => account.ForeignPassedInKey = ForeignPassedInKey)
                .Select(account => account.AccountId);
var parts = db.Parts
                .Where(part => part.IsInExclusiveClub = 1 && accounts.Contains(part.AccountId))
                .Select(part => partId).Distinct();

然后 !accounts.Contains(part.AccountID) 对于 NOT EXISTS

这是关于如何执行“存在”查询的一般思路:

var query = from s in this.CDSEntityManager.Context.cust_task
                     join g in this.CDSEntityManager.Context.cust_task_group on s.cust_task_group_id equals g.cust_task_group_id
                     where s.cust_id == currentAccount.cust_id && g.complaint_flag == true
                     select s;

var isComplaintCustomer = (await query.ExecuteAsync()).Any();

基本思路是:1. 构造您的查询。 2.用Any().

执行