如何在MVC视图中迭代分组的LINQ数据

时间:2012-12-03 17:36:06

标签: c# asp.net-mvc linq

我有两张桌子。一个表称为Occurrence,包含以下内容:

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

另一个表名为Employee,包含以下内容:

EmployeeID | EmployeeName
-------------------------
 1         |Jack
 2         |Jill

我正在尝试将这两个表组合在一起,并最终为每个员工提供一行,以显示我的MVC 4项目中视图中的总点数。所以对于上面的例子我的输出应该是:

Name    | Points
----------------
Jack    |8
Jill    |2

这是我在Controller中尝试过的LINQ查询:

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

这是我的观点:

@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>

当我导航到此视图时,我收到此错误:

  

传递到字典中的模型项的类型为'System.Data.Entity.Infrastructure.DbQuery 1[<>f__AnonymousType3 2 [System.Int32,System.Int32]]',但此字典需要类型的模型项'System.Collections.Generic.IEnumerable`1 [PtoTracker.Occurrence]'。

有人可以帮我理解我应该做的不同吗?

1 个答案:

答案 0 :(得分:1)

您需要新建视图预期类

的实例
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)}
   ).AsEnumerable();


var model = groupedOccurrences.Select(item => new PtoTracker.Occurrence { 
                         Name = item.Name,
                         Total = item.Total });

您的观点期待IEnumerable PtoTracker.Occurrence,但您发送的是IQuerable anonymes类型。