C# 一对多LINQ查询-编译器错误
请参见下面的LINQ查询:C# 一对多LINQ查询-编译器错误,c#,linq,entity-framework-5,C#,Linq,Entity Framework 5,请参见下面的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) }; 学生链接
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) };
学生链接到一门课程。因此,上述课程的价值应该是课程的集合。但是,存在编译器错误(System.ArguementNullException)。我做错了什么
我有能力使用SQL,但我对LINQ是新手。请参阅下面数据库中的SQL:
***学生班***
公立部分班学生
{
公共int id{get;set;}
公共字符串名称{get;set;}
公共可空年龄{get;set;}
公共可空courseid{get;set;}
公共虚拟课程{get;set;}
}
课程班
公共部分课程
{
公共课程()
{
this.Students=newhashset();
}
公共int id{get;set;}
公共字符串名称{get;set;}
公共虚拟ICollection学生{get;set;}
}
您似乎只是想让查询同时检索学生的课程
导航属性。因此,您需要做的就是包含它:
var students = db.Students
.Include(s => s.Course)
.Where(s => s.Name.StartsWith("Bert");
编译器错误说明了什么?数据库中是否有任何name
为空?Student
类,您在其中投影查询,该类与Student
实体相同,您能显示它吗?当该学生没有课程时,d可能为空?请显示更完整的堆栈跟踪,而不仅仅是异常类型。这看起来像是包含课程,而不是我想要的courseid。如何创建IEnumerable返回的学生和课程对象?我尝试过:foreach(测试中的学生s){Course c=s.Course;}在SQL中似乎简单得多。只是想学点新东西。你能解释一下你想要什么样的输出吗?现在你没有任何意义。我想找到一个叫伯特的学生(有一个叫这个名字的学生)。然后我想迭代IEnumerable并构造一个Student对象和一个Course对象。见Bolt19的答案。他/她就快到了。我的回答在什么方面不完全一样?无需构造Student
对象,因为EF将为您这样做。
var students = db.Students
.Include(s => s.Course)
.Where(s => s.Name.StartsWith("Bert");