How to create a simple JOIN LINQ query to fetch data from 2 entities?
The introduction of LINQ increased the power of C# language by providing a way to query the collections using SQL like syntax. In SQL, we often use JOIN queries to join two related table in order to fetch the matching rows. This little code will help you to create a simple join query using LINQ in C#.
Assuming you have 2 entities called Employee and Department in your data model, the below LINQ query will retrieve the Employee details by joining (inner join) Department table to fetch the DepartmentName using the DeptID in Employee table. EmployeeInfoDataContext dbEmp = new EmployeeInfoDataContext(); var query = from emp in dbEmp.Employees join dept in dbEmp.Departments on emp.DeptID equals dept.DeptID select new { EmpID = emp.EmpID, EmpName = emp.EmpName, Age = emp.Age, Address = emp.Address, DeptName = dept.DepartmentName };
The above query will fetch all the matching rows using the related column DeptID similar to SQL inner join query.
|