2009-07-09 123 views
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仍然很陌生,我需要幫助弄清楚如何將它變成左外連接,而不是內連接。如何將這些LINQ連接轉換爲左外連接?

從上面的查詢來看,我希望Agencies表中有所有代理,然後右邊的記錄(EnterpriseID,CorrectedDate等)可以爲空,如果沒有記錄存在。

我很確定我需要使用SelectMany,但我可以使用一些指導將這些連接轉換爲左外連接,所以我列出了所有代理然後右邊的可能記錄。

回答

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, 
}); 
+0

這是什麼?......組加入as ... equals ...到xs = group ...`語法中?我以前沒見過這樣的組,我似乎無法找到任何文檔。 – 2014-08-07 19:43:54

0

Here是如何做到這一點的一個很好的例子。 重要的是不要忘記它們可以帶回的空值 - 這讓我難以忍受一次。

+0

我不認爲這適用。它不會在表中顯示左連接。 – Sentinel 2012-02-15 14:33:18