Introduction

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

Step 1: Create asp.net web application

SQL Script

  1. SELECT p.FirstName, q.ManagerName
  2. FROM Employee p
  3. INNER JOIN Employee q
  4. ON p.ManagerID = q.EmpID

Webform1.aspx

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="Self_Join_using_LINQ.WebForm1" %>
  2. <!DOCTYPE html>
  3. <html xmlns="http://www.w3.org/1999/xhtml">
  4. <head runat="server">
  5. <title></title>
  6. </head>
  7. <body>
  8. <form id="form1" runat="server">
  9. <div>
  10. <asp:GridView ID="GridView1" runat="server"></asp:GridView>
  11. </div>
  12. </form>
  13. </body>
  14. </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. namespace Self_Join_using_LINQ
  8. {
  9. public partial class WebForm1 : System.Web.UI.Page
  10. {
  11. EmployeeDBEntities objEmpEntities = new EmployeeDBEntities();
  12. protected void Page_Load(object sender, EventArgs e)
  13. {
  14. var query = from p in objEmpEntities.Employees
  15. join q in objEmpEntities.Employees on p.ManagerId equals q.EmpId
  16. select new { p.FirstName, q.ManagerName };
  17. GridView1.DataSource = query.ToList();
  18. GridView1.DataBind();
  19. }
  20. }
  21. }

Output of the application looks like this

Summary

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