2012-06-06 175 views
8

我知道的Linq的左聯接是類似這樣的:多個表左連接使用LINQ

var q=from e in db.Employes    
     join o in db.Orders on e equals o.Emoloyee into ords   
     from on in ords.DefautIfEmpty() 
     select new 
     {       
     e.FirstName,      
     e.LastName    
   }; 

那麼如何對多個連接?這裏是我的代碼

var personalInfoQuery = from t in crnnsupContext.Tombstones 
         join p in crnnsupContext.ProvStates on t.ProvinceState equals p.ProvinceStateID 
         join n in crnnsupContext.NursingSchools on t.NursingSchool equals n.SchoolID 
         join i in crnnsupContext.InitialEducations on t.InitialEducation equals SqlFunctions.StringConvert((double)i.InitalEducationID, 1) 
         join g in crnnsupContext.tbl_GraduatedProvCountry on t.GradPovCountry equals g.id 
         where t.RegNumber == _username 
         select new CPersonalInfo 
         { 
          ProvState = p, 
          Tombstone = t, 
          NursingSchool = n, 
          InitialEducation = i, 
          GraduatedProvCountry = g, 
         }; 

每個連接表可以有「空」字段。可以幫助我,謝謝

回答

18

多聯接應該看起來非常相似 - 它變得非常詳細,但我會試試這個。 您也可能需要在最終的where行中進行空檢查。

var personalInfoQuery = from t in crnnsupContext.Tombstones 
         join p in crnnsupContext.ProvStates on t.ProvinceState equals p.ProvinceStateID into group1 
         from g1 ini group1.DefaultIfEmpty() 
         join n in crnnsupContext.NursingSchools on g1.NursingSchool equals n.SchoolID into group2 
         from g2 in group2.DefaultIfEmpty() 
         join i in crnnsupContext.InitialEducations on g2.InitialEducation equals SqlFunctions.StringConvert((double)i.InitalEducationID, 1) into group3 
         from g3 in group3.DefaultIfEmpty() 
         join g in crnnsupContext.tbl_GraduatedProvCountry on g3.GradPovCountry equals g.id into group4 
         from g4 in group4.DefaultIfEmpty() 
         where g4 == null || g4.RegNumber == _username 
         select new CPersonalInfo 
         { 
          ProvState = p, 
          Tombstone = t, 
          NursingSchool = n, 
          InitialEducation = i, 
          GraduatedProvCountry = g, 
         }; 

似乎有做外的另一種方式加入很好,但不必東西來測試它在我什至不知道是否有可能在這種情況下使用它 - 檢查出的答案對這個職位如果你有興趣: outer join in linq

+0

非常感謝你! – pita

+2

這樣的陳述的問題是它的翻譯。只有第一次連接將被轉換爲左連接,其他連接將會是內連接,並允許空值。 – Rufix

+0

搜索了幾個例子,這是我唯一的例子。 –