Linq将结果联接到List
本文关键字:List 结果 Linq | 更新日期: 2023-09-27 17:57:43
这里有一个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>
,这样我就可以返回它。
有人知道怎么做吗?
如果我理解正确,您正在寻找将结果转换为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
类的列表)
您正在投影到匿名类型,而不是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();
还没有测试过,但请尝试一下;你需要投影到正确的类型:
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);