I have two tables. One table is called Occurrence that contains the following:
OccurrenceID | EmployeeID | OccurrenceDate | Points | Comment
-------------------------------------------------------------
1 |1 |2012-01-01 |5 |yada
2 |1 |2012-02-01 |3 |blah
3 |2 |2012-03-01 |2 |yada
The other table is called Employee and contains the following:
EmployeeID | EmployeeName
-------------------------
1 |Jack
2 |Jill
I am trying to group these two tables together and end up with a single line for each employee that will show the total points in a view in my MVC 4 project. So for the above example my output should be:
Name | Points
----------------
Jack |8
Jill |2
Here is the LINQ query that I’ve tried in my Controller:
var groupedOccurrences = from o in db.Occurrences.Include(o => o.Employee)
where o.OccurrenceDate >= beginDate
&& o.OccurrenceDate <= endDate
group o by new {o.EmployeeID, o.Points} into g
select new {
Name = g.Key.EmployeeID,
Total = g.Sum(o => o.Points)
};
return View(groupedOccurrences);
And here is my View:
@model IEnumerable<PtoTracker.Occurrence>
<table>
<tr>
<th>
Employee
</th>
<th>
Total Pts.
</th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Employee.EmployeeName)
</td>
<td>
@Html.DisplayFor(modelItem => item.Points)
</td>
</tr>
}
</table>
When I navigate to this view I get this error:
The model item passed into the dictionary is of type ‘System.Data.Entity.Infrastructure.DbQuery
1[<>f__AnonymousType32[System.Int32,System.Int32]]’, but this dictionary requires a model item of type ‘System.Collections.Generic.IEnumerable`1[PtoTracker.Occurrence]’.
Can someone help me understand what I should be doing differently?
You need to new up instances of your view expected class
your view is expecting
IEnumerableofPtoTracker.Occurrencebut you are sending it anIQuerableof anonymes type instead.