Reputation: 200
Here is a linq inner join which returns what I want
var innerJoinQuery =
from employee in DbSet
join department in DbContext.Set<Departments>() on employee.DepartmentID equals department.ID
select new { ID = employee.ID, FirstName = employee.FirstName, LastName = employee.LastName, DepartmentID = employee.DepartmentID, DepartmentName = department.Name };
List<Employees> innerjoinresult_as_employees_list = innerJoinQuery.AsEnumerable().Cast<Employees>().ToList();
Model of Employees is:
public class Employees
{
public int ID { get; set; }
[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
public int DepartmentID { get; set; }
[NotMapped]
public string DepartmentName { get; set; }
}
My problem is that I cannot have var innerJoinQuery as List<Employees>
so I can return it.
Does anyone knows how to do this?
Upvotes: 2
Views: 13655
Reputation: 218712
If i understood you correctly, you are looking for a way to transform your result to a list of Employees
instances.
You can do that by updating the projection part of your LINQ statement. Currently it projects to an antonymous object. you want to project to Employees
type
var innerjoinresult_as_employees_list =(from employee in DbSet
join department in DbContext.Set<Departments>()
on employee.DepartmentID equals department.ID
select new Employees {
ID = employee.ID,
FirstName = employee.FirstName,
LastName = employee.LastName,
DepartmentID = employee.DepartmentID,
DepartmentName = department.Name }
).ToList();
The result (variable innerjoinresult_as_employees_list
's value will be a list of Employees
class)
Upvotes: 1
Reputation: 545
Haven't tested this, but try it out; you need to project to the correct type:
var innerJoinQuery =
(from employee in DbSet
join department in DbContext.Set<Departments>() on employee.DepartmentID equals department.ID
select new Employees{ ID = employee.ID, FirstName = employee.FirstName, LastName = employee.LastName, DepartmentID = employee.DepartmentID, DepartmentName = department.Name }).ToList();
List<Employees> employees = new List<Employees>(innerJoinQuery);
Upvotes: 1
Reputation: 152521
You are projecting to an anonymous type, not Employee
objects. Change your query to:
var innerJoinQuery =
from employee in DbSet
join department in DbContext.Set<Departments>()
on employee.DepartmentID equals department.ID
select new Employee { ID = employee.ID,
FirstName = employee.FirstName,
LastName = employee.LastName,
DepartmentID = employee.DepartmentID,
DepartmentName = department.Name
};
List<Employees> innerjoinresult_as_employees_list = innerJoinQuery.ToList();
Upvotes: 1