Working With Inner Join Using LINQ And Lambda

Here, you will learn how to work with inner join using Linq and Lambda

Inner Join
 
Inner join returns only those records or rows that match or exist in both the tables. In other words, it gives a common pattern from both tables.
 
SQL Syntax
  1. SELECT column_name(s)  
  2. FROM table1  
  3. INNER JOIN table2 ON table1.column_name = table2.column_name;  
Now design the tables and insert the dummy records as below
 
Now Integrate database tables to your application using Entity framework database first approach



Here CSharpCornerEntities is the Entity framework context name, Now let us see the example using these tables
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6. namespace InnerJoin {  
  7.     class Program {  
  8.         static void Main(string[] args) {  
  9.             using(CSharpCornerEntities databaseEntities = new CSharpCornerEntities()) {#  
  10.                 region InnerJoin with Linq  
  11.                 //deffered query exection  
  12.                 var linqQuery = from emp in databaseEntities.Employees  
  13.                 join dep in databaseEntities.Departments  
  14.                 on emp.ID equals dep.EmpID  
  15.                 select new {  
  16.                     emp.ID,  
  17.                         emp.Name,  
  18.                         dep.DepartmentName  
  19.                 };  
  20.                 Console.WriteLine("\n\t Employee Data with Inner join Using Linq Query");  
  21.                 //immediate query execution  
  22.                 foreach(var empData in linqQuery) {  
  23.                     Console.WriteLine("ID : " + empData.ID + ", Name : " + empData.Name + ", Department : " + empData.DepartmentName);  
  24.                 }#  
  25.                 endregion# region InnerJoin with Lambda  
  26.                 //deffered query exection  
  27.                 var LambdaQuery = databaseEntities.Employees.Join(databaseEntities.Departments, e => e.ID, d => d.EmpID, (e, d) => new {  
  28.                     e.ID, e.Name, d.DepartmentName  
  29.                 });  
  30.                 Console.WriteLine("\n\t Employee Data with Inner join Using Linq Lambda");  
  31.                 //immediate query execution  
  32.                 foreach(var empData in LambdaQuery) {  
  33.                     Console.WriteLine("ID : " + empData.ID + ", Name : " + empData.Name + ", Department : " + empData.DepartmentName);  
  34.                 }#  
  35.                 endregion  
  36.             }  
  37.         }  
  38.     }  
  39. }  

Now run your application



I hope it's helpful