如何使用Linq to Entities查询同一表中存在和不存在

时间:2017-05-17 15:11:19

标签: c# asp.net entity-framework asp.net-core linq-to-entities

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

我想查询表格,找到属于专属俱乐部且不属于专属俱乐部的独特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编写它。另外,如果您需要更多信息,请与我们联系。

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

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

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()执行。