MVC 错误 "requires ienumerable instead of list"

MVC error "requires ienumerable instead of list"

试图显示 2 个表、员工和部门的值,所以我尝试执行 linq sql 查询,但是当我在网络浏览器中打开我的应用程序时它不起作用。 MVC 的新手,这是我第一次使用 linq to sql 所以我不确定出了什么问题!

我的错误:

The model item passed into the dictionary is of type 'System.Collections.Generic.List1[<>f__AnonymousType74[System.String,System.String,StaffDetails.Models.Department,StaffDetails.Models.Site]]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[StaffDetails.Models.Staff]'.

索引视图

    public ActionResult Index()
    {
        IList<Staff> staffList = new List<Staff>();

        var query = (from s in db.Staffs
                     from d in db.Departments
                     where s.DeptID == d.DeptID
                     select new
                     {
                         name = s.Name,
                         email = s.Email,
                         department = s.Department,
                         site = d.Site
                     }
                     ).ToList();

        return View(query);
    }

问题是您传递的是匿名类型,但您的视图需要 IEnumerable<Staff>,因此在投影您的 LINQ 查询时,您需要像这样投影 Staff 类型:-

List<Staff> query = (from s in db.Staffs
                     from d in db.Departments
                     where s.DeptID == d.DeptID
                     select new Staff //here
                     {
                         Name = s.Name,
                         Email= s.Email,
                         Department = s.Department,
                         Site = d.Site
                     }).ToList();

更新:

好的,所以您的 Staff 是一个映射实体,因此在这种情况下您不应该能够直接映射它。您需要一个 DTO 或者您可以首先投影匿名类型并使用 AsEnumerable() 在 linq-to-objects 中进行操作,然后像这样从那里投影:-

IEnumerable<Staff> staffList = (from s in db.Staffs
                     from d in db.Departments
                     where s.DeptID == d.DeptID
                     select new
                     {
                         name = s.Name,
                         email = s.Email,
                         department = s.Department,
                         site = d.Site
                     }).AsEnumerable()
                       .Select(x => new new Staff 
                          {
                             Name = x.name,
                             Email= x.email,
                             Department = x.department,
                             Site = x.site
                          });