请参阅下面的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) };
学生链接到一门课程。因此,上述课程的价值应该是课程的集合。但是,存在编译器错误(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; }
}
答案 0 :(得分:1)
您似乎只是试图让您的查询也为您的学生检索Course
导航属性。因此,您需要做的只是Include
:
var students = db.Students
.Include(s => s.Course)
.Where(s => s.Name.StartsWith("Bert");