2

我有两张桌子。一个表称为 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

这是我在控制器中尝试过的 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__AnonymousType32[System.Int32,System.Int32]]”,但此字典需要类型为“System.Collections.Generic.IEnumerable”的模型项`1[PtoTracker.Occurrence]'。

有人可以帮助我了解我应该做些什么不同的事情吗?

4

1 回答 1

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是匿名类型的。

于 2012-12-03T17:39:30.057 回答