MVC viewmodel和linq查询

时间:2016-09-29 21:08:09

标签: linq viewmodel asp.net-mvc-5

我终于(4周后)获得了一个MVC5项目的结果,并且进展顺利。 现在我试图“限制”结果的数量,并标记错误:

'Stoopid' is a type, which is not valid in the given context
'Student' is a type, which is not valid in the given context

以下是模型:

namespace viewModelA
{
    public class Teacher
    {
        public int TeacherId { get; set; }
        public string Code { get; set; }
        public string Name { get; set; }
    }
    public class Student
    {
        public int StudentId { get; set; }
        public string Code { get; set; }
        public string Name { get; set; }
        public string EnrollmentNo { get; set; }
    }
    public class Stoopid
    {
        [Key]
        public int StoopID { get; set; }
        public DateTime stopDt { get; set; }
    }
    public class ViewModel
    {
        public IEnumerable<Teacher> Teachers { get; set; }
        public IEnumerable<Student> Students { get; set; }
        public IEnumerable<Stoopid> Stoopids { get; set; }
    }
}

这是linq查询 - 注意老师很好,但学生和Stoopid不是。它们都在同一个.cs文件中。我错过了什么吗?

var result = (from t in Teacher
        join s in  Student on t.TeacherId equals s.StudentId
        join st in Stoopid on s.StudentId equals st.StoopID
         where t.TeacherId == 2
         select new
         {
          TeacherID= t.TeacherId,
          Code = t.Code,
           t.Name,
           s.StudentId,
          sCode =s.Code,
          sName=s.Name,
          stopDt= st.stopDt
         })

编辑:我将相关代码添加到HomeController。我也通过LINQPad5运行它,它工作正常,所以我不知道这是什么交易 HomeController

1 个答案:

答案 0 :(得分:0)

您在Linq查询中引用了类名,这就是它抛出该错误的原因。您需要引用实际的List对象。

var result = (from t in mymodel.Teachers
    join s in mymodel.Students on t.TeacherId equals s.StudentId
    join st in mymodel.Stoopids on s.StudentId equals st.StoopID
     where t.TeacherId == 2
     select new
     {
      TeacherID= t.TeacherId,
      Code = t.Code,
       t.Name,
       s.StudentId,
      sCode =s.Code,
      sName=s.Name,
      stopDt= st.stopDt
     })