views:

220

answers:

2
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,

                                      });

So, I'm still pretty new to LINQ to SQL and I need help figuring out how to turn this into a left outer join, rather than an inner join.

From that query above, I'm looking to have ALL agencies from the Agencies table, and then the records on the right (EnterpriseID, CorrectedDate, etc) can be null, etc if no records exist.

I'm fairly certain I need to use SelectMany but I could use some guidance turning those joins into LEFT OUTER JOINS, so I have a list of all agencies then their possible records on the right.

+1  A: 

Here is a good example of how to do it. It's important to not forget about null values that these can bring back -- this bit me hard once.

Nazadus
+1  A: 

Below is some code that can get you started.

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,
});
Bryan Roth