Smiley
Smiley

Reputation: 3437

LINQ-to-Entity Joined Table Return

I have two tables as follows:

Departments:
   DeptID   (PK)
   DeptName
   ...

Employees: 
   EmpID    (PK)
   DeptID   (FK)
   EmpName
   ...

and I have a query using LINQ as follows:

public List<Employee> GetEmployee(int deptID)
{
    var query = from e in mdc.Employees
                join d in mdc.Departments on e.DeptID equals d.DeptID
                where e.DeptID == deptID
                select new { e.EmpID, e.EmpName, d.DeptName };

    return query.ToList();
}

Now my question is this. I would like to select the fields EmpID, EmpName, and DeptName. But what will my return type be? This one returns an error because this query returns a GenericList as opposed to my List<Employee>.

Upvotes: 0

Views: 987

Answers (1)

Jayantha Lal Sirisena
Jayantha Lal Sirisena

Reputation: 21366

You need to create another class with required properties like this,

public class NewType{
public EmpID{get;set;}
//other fields here
}  

and then select ,

public List<NewType> GetEmployee(int deptID)
{
    var query = from e in mdc.Employees
                join d in mdc.Departments on e.DeptID equals d.DeptID
                where e.DeptID == deptID
                select new NewType{ e.EmpID, e.EmpName, d.DeptName };

    return query.ToList();
}

Upvotes: 1

Related Questions