Wednesday, February 23, 2011

Joins in Linq to Sql

Linq to Sql given us excellent feature of joins, the two common joins are the inner join (or just join in LINQ) and the left join. Inner join returns all the rows that are matched in both tables, left join returns all rows from the left table, even if there are no matches in the right table
Sample pieces for inner join and left join
Inner Join
var empDetails = from emp in objEmp.Employees
                         join dept in objEmp.Depts on emp.Deptid equals dept.DeptId
                         select new
                         {
                             emp.EmpName,
                             emp.Designation,
                             emp.Location,
                             dept.DeptName
                         };

Left Join
var empDetails = from emp in objEmp.Employees
                join dept in objEmp.Depts on emp.Deptid equals dept.DeptId into empdet
                         from de in empdet.DefaultIfEmpty()
                         select new
                         {
                             emp.EmpName,
                             emp.Designation,
                             emp.Location,
                             de.DeptName
                         };

Pro LINQ: Language Integrated Query in C# 2008 (Windows.Net) 

No comments:

Post a Comment