2

2つのテーブルがあります。1つのテーブルは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

もう1つのテーブルはEmployeeと呼ばれ、次のものが含まれています。

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

これらの2つのテーブルをグループ化しようとすると、MVC 4プロジェクトのビューに合計ポイントが表示される、従業員ごとに1行になります。したがって、上記の例では、出力は次のようになります。

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.DbQuery2 1[<>f__AnonymousType3[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 に答える