9

我知道 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,
                         };

每个连接表都可以有“空”字段。有什么可以帮助我的,谢谢

4

1 回答 1

20

多连接应该看起来非常相似 - 它变得非常冗长,但我会尝试一下。您可能还需要在最后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加入linq

于 2012-06-06T20:18:25.453 回答