【问题标题】:MVC viewmodel and a linq queryMVC 视图模型和 linq 查询
【发布时间】:2017-02-08 08:31:33
【问题描述】:

我终于(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 查询 - 注意 Teacher 很好,但 Student 和 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

【问题讨论】:

  • 您是否尝试返回包含 3 种类型的视图模型?
  • 是的 - 我正在返回“ViewModel”..这就是我如此困惑的原因。
  • 您使用的是代码优先还是数据库优先的方法?如果使用代码优先方法,您确定您已经定义了数据集?
  • Steffsww- 我首先使用代码。我添加了 HomeController 的代码。

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


【解决方案1】:

您在 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
     })

【讨论】:

    猜你喜欢
    • 2020-12-16
    • 1970-01-01
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多