2013-02-19 42 views
3

我试图从我的控制器传递一个LINQ列表对象到我的视图。 linq对象包含引发某种错误的分组。我只想在视图中显示分组对象。 linq语句完美地工作,但显示语句不!任何帮助将不胜感激!传递分组LINQ对象查看

控制器

 public ViewResult StudentAttendanceForYear(int id) 
    { 

     DateTime finDate = System.DateTime.Today; 
     DateTime strtDate = DateTime.Today.AddMonths(-6); 


     var chosenStudent = (from t in db.ClassInstanceDetails.Include("Student") 
           where (t.Attendance == false) && (t.StudentID == id) 
           && (t.ClassInstance.Date > strtDate) && (t.ClassInstance.Date < finDate) 
           group t by new { t.ClassInstance.Date.Year, t.ClassInstance.Date.Month, t.ClassInstance.Date.Day } into grp 
           select new 
           { 

            absentDate = grp.Key, 
            numAbsences = grp.Count(t => t.Attendance == false) 

           }).ToList(); 



     return View(chosenStudent.ToList()); 
    } 

视图

我试图改变我的观点,以

@model IEnumerable<System.Linq.IGrouping<object, FYPSchoolApp.DAL.ClassInstanceDetail>> 

但仍没有运气,我不断收到以下错误:

模型项目传入字典的类型是'System.Collections.Generic.List 1[<>f__AnonymousType7 2 [<> f__AnonymousType6 3[System.Int32,System.Int32,System.Int32],System.Int32]]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable 1 [System.Linq.IGrouping`2 [System.Object,FYPSchoolApp.DAL.ClassInstanceDetail]]'。

回答

2

不要试图将匿名类型作为模型传递到视图中。

你需要的是一个ViewModel:

public class AbsentCountViewModel 
{ 
    public DateTime absentDate { get; set; } 
    public int numAbsences { get; set; } 
} 

然后更改您的查询,选择到您的视图模型

var chosenStudent = 
    (from t in ... 
    group t by new 
    { 
      t.ClassInstance.Date.Year, 
      t.ClassInstance.Date.Month, 
      t.ClassInstance.Date.Day 
    } into grp 
    select new 
    { 
     absentDate = grp.Key, 
     numAbsences = grp.Count(t => t.Attendance == false) 
    }).ToList() 
    // you need to do the select in two steps 
    // because EF cannot translate the new DateTime 
    .Select(item => new AbsenctCountViewModel 
    { 
     absentDate = new DateTime(item.absentDate.Year, 
           item.absentDate.Month, 
           item.absentDate.Day) 
     numAbsences = item.numAbsences 
    }).ToList(); 

return View(chosenStudent); 

终于可以与@model访问视图的结果:

@model List<AbsenctCountViewModel> 
+0

非常感谢您的回复,我对这一切都比较陌生!我创建了VIewModel并输入了你的代码,但是现在我得到这个错误“LINQ to Entities只支持无参数的构造函数和初始化器。”任何想法如何解决它? – 2013-02-19 21:24:35

+0

对不起,这是由'新日期时间(...'造成的,并有多种方法可以解决它...我会更新我的答案。 – nemesv 2013-02-19 21:29:47

+0

修复它!非常非常非常!它可以安全地说我永远不会已经解决了我自己! – 2013-02-19 21:49:55