How to Perform Self Outer JOIN using LINQ

Introduction

In this blog we will see how to perform self outer join using LINQ.

Step 1: Create asp.net web application

Webform1.aspx

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="SelfOuterJoin_LINQ.WebForm1" %>  
  2.   
  3. <!DOCTYPE html>  
  4.   
  5. <html xmlns="http://www.w3.org/1999/xhtml">  
  6. <head runat="server">  
  7.     <title></title>  
  8. </head>  
  9. <body>  
  10.     <form id="form1" runat="server">  
  11.     <div>  
  12.         <asp:GridView ID="GridView1" runat="server"></asp:GridView>  
  13.     </div>  
  14.     </form>  
  15. </body>  
  16. </html>  

Webform1.aspx.cs

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.UI;  
  6. using System.Web.UI.WebControls;  
  7.   
  8. namespace SelfOuterJoin_LINQ  
  9. {  
  10.     public partial class WebForm1 : System.Web.UI.Page  
  11.     {  
  12.         EmployeeDBEntities objEmpEntities = new EmployeeDBEntities();  
  13.         protected void Page_Load(object sender, EventArgs e)  
  14.         {  
  15.             var query = (from r in objEmpEntities.Employees  
  16.                          join q in objEmpEntities.Employees on r.EmpId equals q.ManagerId into result  
  17.                          from emp in result.DefaultIfEmpty()  
  18.                          select new  
  19.                          {  
  20.                              r.FirstName,  
  21.                              r.LastName,  
  22.                              emp.ManagerName  
  23.                          }).ToList();  
  24.   
  25.             GridView1.DataSource = query;  
  26.             GridView1.DataBind();  
  27.         }  
  28.     }  
  29. }  

Output of the application looks like this

Summary

In this blog we have seen how we can perform self-outer join using LINQ. Happy coding!

Ebook Download
View all
Learn
View all
MVC Corporation is consulting and IT services based company.