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 

最佳答案 使用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();
点赞