user4840466
user4840466

Reputation:

MVC error "requires ienumerable instead of list"

Trying to display values from 2 tables, staff and department so i tried to perform a linq sql query but it doesn't work when i open my application in the web browser. New to MVC and this is my first time using linq to sql so I'm not sure whats wrong!

My error:

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]'.

Index view

    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);
    }

Tables

enter image description here

Upvotes: 2

Views: 629

Answers (1)

Rahul Singh
Rahul Singh

Reputation: 21795

The problem is you are passing an anonymous type but your view expects IEnumerable<Staff>, so while projecting your LINQ query you need to project Staff type like this:-

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();

Update:

Okay so your Staff is a mapped entity so in that case you should not be able to map it directly. You either need a DTO or alternatively you can first project the anonymous type and bring the operation in linq-to-objects using AsEnumerable() and then project from there like this:-

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
                          });

Upvotes: 3

Related Questions