CODEDIGEST
Home » CodeDigest
Search
 

Technologies
 

How to create a simple JOIN LINQ query to fetch data from 2 entities in C#?
Submitted By Satheesh Babu B
On 6/14/2009 7:12:27 AM
Tags: CodeDigest,LINQ  

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.

Do you have a working code that can be used by anyone? Submit it here. It may help someone in the community!!

Recent Codes
  • View All Codes..