Search code examples
c#sqllinq

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


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 

Solution

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