如何在我们在sql中使用的linq中使用左连接?

时间:2016-05-29 07:23:57

标签: c# sql linq

如何在Linq中使用Left join来编写SQL查询?

select 
    p.Name, p.Family,
    E.EmployTypecode, E.employtypeName, E.EmplytyppeTye 
from 
    personnel as p
left join 
    Employee as E on E.EmployTypecode = p.EmployTypecode 

4 个答案:

答案 0 :(得分:1)

使用Join关键字而不是Left join,必须使用“INTO”关键字和“DefaultIfEmpty()”方法,因为右表返回null值。

   var query = from p in personnel 
               join e in Employee on p.EmployTypecode equals e.EmployTypecode into t
               from nt in t.DefaultIfEmpty()
               orderby p.Name

    select new
    {
        p.Name, p.Family,
        EmployTypecode=(int?)nt.EmployTypecode,  // To handle null value if Employtypecode is specified as not null in Employee table.
        nt.employtypeName, nt.EmplytyppeTye
    }.ToList();

答案 1 :(得分:0)

这样做:

var query = 
from  p in personnel
join e in Employee 
    on p.EmployTypecode equals e.EmployTypecode
into temp
from j in temp.DefaultIfEmpty()
select new
{
    name = p.name,
    family = p.family,
    EmployTypecode = String.IsNullOrEmpty(j.EmployTypecode) ? "" : j.EmployTypecode,
    ......
}

答案 2 :(得分:0)

var q=(
              from pd in dataContext.personnel 
              join od in dataContext.Employee 
                  on pd.EmployTypecode equals od.EmployTypecode 
                  into t 
              from rt in t.DefaultIfEmpty() 
              orderby pd.EmployTypecode 
              select new 
              {  
                  EmployTypecode=(int?)rt.EmployTypecode,
                  pd.Name, 
                  pd.Family,  
                  rt.EmplytyppeTye 
              }
         ).ToList(); 

答案 3 :(得分:0)

为什么不使用SQL查询将EF转换为LIST。 在EF 6.1中

 public class personnel
    {
        public String Name { get; set; }
        public String Family { get; set; }
        public String EmployTypecode { get; set; }
        public String employtypeName { get; set; }
        public String EmplytyppeTye { get; set; }
    }

List<personnel> personnels = dbentities.Database.SqlQuery<personnel>(@"select 
    p.Name, p.Family,
    E.EmployTypecode, E.employtypeName, E.EmplytyppeTye 
from 
    personnel as p
left join 
    Employee as E on E.EmployTypecode = p.EmployTypecode ").ToList();