我正在使用实体框架并具有以下类
class Student
{
[Key]
public virtual int StudentID {get; set;}
public virtual string StudentName {get; set;}
public virtual ICollection<Note> Notes {get; set;}
}
class Note
{
[Key]
public virtual int NoteID {get; set;}
public virtual int StudentID {get; set;}
public virtual string Message {get; set;}
}
class StudentDBContext:DbContext
{
public DbSet<Student> Students { get; set; }
public DbSet<Note> Notes { get; set; }
}
总而言之,我有一班学生,每个人都有很多笔记。现在,我想使用 Linq 检索和显示特定学生的所有笔记。所以我尝试
using (StudentDBContext a = new StudentDBContext())
{
var b = from c in a.Student
where c.StudentID == 1001
select c;
var currStudent = b.FirstOrDefault();
Console.WriteLine(currStudent.StudentName);
//display all the messages of the current student
foreach (var currNote in currStudent.Notes)
Console.WriteLine(currNote.Message);
}
在上面的代码中,我的 foreach 块总是失败,因为 Student.Notes 总是为空。我是否错过了初始化 Student.Notes 并从数据库中填充它的一些步骤?