How can I use Left join in linq that we use in sql?

纵饮孤独 提交于 2020-08-02 09:41:06

问题


How can I use Left join in Linq that I write SQL query?

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 

回答1:


Use Join keyword instead of Left join and it is mandatory to use "INTO" keyword and "DefaultIfEmpty()" method as right table returns null value.

   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();



回答2:


Do it like this :

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,
    ......
}



回答3:


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(); 



回答4:


Why dont use SQL query to convert EF to LIST. In EF 6.1

write

 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();


来源:https://stackoverflow.com/questions/37507297/how-can-i-use-left-join-in-linq-that-we-use-in-sql

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!