user3198688
user3198688

Reputation: 305

Linq - Join multiple tables and get output into single result set

I have a Employee table which has DepartmentId column which is a foreignkey to Department table, the Department table has DepartmentId column and DepartmentName column..

In the search functionality the End user gives DepartmentName and i need display all the Employee details who are part of that department.

how can i join the Department table to the Employee table

 List<Employee> employees = new List<Employee>();

 employees = EMPDB.Employees.AsNoTracking().select( e => new Employee()
 {
 FirstName = e.FirstName,
 LastName = e.LastName,
 DepartmentName =

 })where(e.Departmentid == depName).ToList();

I would like to have my employees list like the above

Upvotes: 0

Views: 166

Answers (1)

Rahul
Rahul

Reputation: 77876

You can perform a LEFT JOIN with Departments table like

var data = (from emp in EMPDB.Employees
                join dept in EMPDB.Departments on emp.DepartmentId equals dept.Id 
                && dept.DepartmentName == depName into joindata
                from joindata in joindata.DefaultIfEmpty()
                select new 
                { 
                 FirstName = emp.FirstName, 
                 LastName = emp.Lastname,
                 DepartmentName = !string.IsNullOrEmpty(dept.DepartmentName) ? dept.DepartmentName : "No Department" 
                };).ToList();

Upvotes: 0

Related Questions