这是一个linq内部联接,返回我想要的内容
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();
员工模型是:
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; }
}
我的问题是我不能将var innerJoinQuery作为List<Employees>
,所以我可以将它返回。
有谁知道怎么做?
答案 0 :(得分:1)
如果我理解正确,那么您正在寻找一种将结果转换为Employees
个实例列表的方法。
您可以通过更新LINQ语句的投影部分来实现。目前它投射到一个反对象。您想投射到Employees
类型
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();
结果(变量innerjoinresult_as_employees_list
的值将是Employees
类的列表)
答案 1 :(得分:1)
您正在投射到匿名类型,而不是Employee
个对象。将您的查询更改为:
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();
答案 2 :(得分:1)
没有测试过,但试试看;你需要投射到正确的类型:
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);