Adalat  Khan

Adalat Khan

  • 599
  • 1.5k
  • 848k

Tables joining using LINQ

Mar 1 2019 6:04 AM
I have two tables one is Employee table and another is Departments table. The Employee table and Departments tables are linked using foriegn key relation. The Employee table contains the following fields:
 
EmpCode, EmpName, EmpBirthDate, EmpDepttCode
 
The Departments table contains the following fields:
DepttCode, DepttName
 
I want to display the following fields from these two tables using LINQ:
 
EmpCode, EmpName, EmpBirthDate, DepttName
 
I want to display the fields EmpCode, EmpName, EmpBirthDate from the Employee table and the field DepttName from the Department table. I have tried the following:
 
First of all i created a ModelView for the required fileds as the following structure:
 
public class RetrieveEmployeeDetails
{
[Key]
public string EmpCode { get; set; }
public string EmpName { get; set; }
public DateTime? EmpBirthDate { get; set; }
public DepttName {get; set;}
}
 
Following is my LINQ Query:
 
public IActionResult SearchEmployeeRecord()
{
var empRecord = from emp in dbContext.Employee
join d in dbContext.Departments on emp.EmpDepttCode equals d.DepttCode
select new RetrieveEmployeeDetails
{
EmpCode = emp.EmpCode,
EmpName = emp.EmpFullName,
EmpBirthDate = emp.EmpBirthDate,
DepttName = d.DepttName
};
return PartialView(empRecord);
 }
 
 My above query retrieves data but it does not display the field DepttName. Instead of the field DepttName it displays the DepttCode not DepttName. Why it does not display the field DepttName. Please find out the error in my above LINQ query joining.
 

Answers (2)