这是一个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类的列表)

关于c# - Linq将结果加入列表,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38444853/

10-12 23:54