Introduction

In this blog we will see how to perform self join using linq to sql.

Step 1: Create ASP.NET Webforms application

Webform1.aspx

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="SelfJoin_LINQtoSQL.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 SelfJoin_LINQtoSQL
  8. {
  9. public partial class WebForm1 : System.Web.UI.Page
  10. {
  11. DataClasses1DataContext objContext = new DataClasses1DataContext();
  12. protected void Page_Load(object sender, EventArgs e)
  13. {
  14. var query = (from r in objContext.Employees
  15. join s in objContext.Employees
  16. on r.EmpId equals s.DeptId
  17. select new
  18. {
  19. FirstName = r.FirstName
  20. ,LastName = r.LastName
  21. });
  22. GridView1.DataSource = query;
  23. GridView1.DataBind();
  24. }
  25. }
  26. }

Output of the application looks like this

Summary

In this blog we have seen how we can perform self join using linq to sql. Happy coding!