多个表使用Linq保持联接

时间:2012-06-06 19:14:52

标签: asp.net 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,
                         };

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

1 个答案:

答案 0 :(得分: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