【问题标题】:One to Many LINQ Query - compiler error一对多 LINQ 查询 - 编译器错误
【发布时间】:2016-12-22 15:26:01
【问题描述】:

请参阅下面的 LINQ 查询:

var test = from s in db.Students
           join c in db.Courses on s.courseid equals c.id into d
           where s.name.StartsWith("Bert")
           select new Student { id=s.id,name=s.name, Course = d.Select(x => x.name) };

学生链接到一门课程。因此,上述 Course 的值应该是课程的集合。但是,存在编译器错误 (System.ArguementNullException)。我做错了什么?

我能够胜任使用 SQL,但是我是 LINQ 的新手。请查看以下数据库中的 SQL:

***Student Class***
  public partial class Student
    {
        public int id { get; set; }
        public string name { get; set; }
        public Nullable<int> age { get; set; }
        public Nullable<int> courseid { get; set; }

        public virtual Course Course { get; set; }
    }

    Course Class

 public partial class Course
    {
        public Course()
        {
            this.Students = new HashSet<Student>();
        }

        public int id { get; set; }
        public string name { get; set; }

        public virtual ICollection<Student> Students { get; set; }
    }

【问题讨论】:

  • 编译器错误说明了什么?
  • 数据库中是否有任何name 为空?
  • Student 您投影查询的类与您的Student 实体相同,您能展示一下吗?
  • 当该学生没有课程时,可能 d 为空?
  • 请显示更完整的堆栈跟踪,而不仅仅是异常类型。

标签: c# linq entity-framework-5


【解决方案1】:

您似乎只是想让您的查询也为您的学生检索Course 导航属性。因此,您需要做的就是Include它:

var students = db.Students
    .Include(s => s.Course)
    .Where(s => s.Name.StartsWith("Bert");

【讨论】:

  • 这看起来像是包含课程而不是我想要的 courseid。我将如何创建 IEnumerable 返回的学生和课程对象?我试过: foreach(Student s in test) { Course c = s.Course; }
  • 在 SQL 中似乎要简单得多。只是想学习一些新东西。
  • 你能准确解释你想要什么输出吗?现在你没有任何意义。
  • 我要查找姓名为:Bert 的学生(有一名学生使用此姓名)。然后我想迭代 IEnumerable 并构造一个 Student 对象和一个 Course 对象。请参阅 Bolt19 的答案。他/她快到了。
  • 我的答案在什么方面不完全一样?无需构造 Student 对象,因为 EF 会为您完成。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多