1
var auditAgencyRecords = (from ag in db.Agencies
                                      join ara in db.AuditRuleAccounts on ag.Agency_Id equals ara.AgencyID
                                      join arr in db.AuditRuleResults on ara.AuditRuleAccountID equals arr.AuditRuleAccountID
                                      join are in db.AuditRuleEnterprises on arr.AuditRuleEnterpriseID equals are.AuditRuleEnterpriseID
                                      where (rules.Select(r => r.EnterpriseID).Contains(arr.AuditRuleEnterpriseID))
                                      select new
                                      {

                                          AgencyID = ag.Agency_Id,
                                          AgencyName = ag.Agency_Name,
                                          AuditRuleEnterpriseID = arr.AuditRuleEnterpriseID,
                                          AuditRuleEnterpriseName = are.OverrideDisplayName,
                                          CorrectedDate = arr.CorrectedDate,
                                          NbrDaysToCorrect = arr.NbrDaysToCorrect,

                                      });

所以,我对 LINQ to SQL 还是很陌生,我需要帮助弄清楚如何将它变成左外连接,而不是内连接。

从上面的查询中,我希望从 Agencies 表中获取所有代理,然后如果不存在记录,则右侧的记录(EnterpriseID、CorrectedDate 等)可以为空,等等。

我相当确定我需要使用 SelectMany,但我可以使用一些指导将这些连接转换为 LEFT OUTER JOINS,所以我有一个所有机构的列表,然后他们可能的记录在右边。

4

2 回答 2

2

下面是一些可以帮助您入门的代码。

var auditAgencyRecords = (
from ag in db.Agencies
group join ara in db.AuditRuleAccounts on ag.Agency_Id equals ara.AgencyID into AgAra = group
from w in AgAra.DefaultIfEmpty()
group join arr in db.AuditRuleResults on ara.AuditRuleAccountID equals arr.AuditRuleAccountID into AraArr = group
from x in AraArr.DefaultIfEmpty()
group join are in db.AuditRuleEnterprises on arr.AuditRuleEnterpriseID equals are.AuditRuleEnterpriseID into ArrAre = group
from y in ArrAre.DefaultIfEmpty()
where (rules.Select(r => r.EnterpriseID).Contains(arr.AuditRuleEnterpriseID))
select new
{    
     AgencyID = w.Agency_Id,
     AgencyName = w.Agency_Name,                                           
     AuditRuleEnterpriseID = y.AuditRuleEnterpriseID,
     AuditRuleEnterpriseName = y.OverrideDisplayName,
     CorrectedDate = w.CorrectedDate,
     NbrDaysToCorrect = w.NbrDaysToCorrect,
});
于 2009-07-09T20:31:47.973 回答
0

是如何做到这一点的一个很好的例子。重要的是不要忘记这些可以带回的空值——这让我很难过一次。

于 2009-07-09T19:54:27.037 回答