我正在使用 Entity Framework 并有以下类
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 block 总是失败,因为 Student.Notes 始终为 null。我是否缺少初始化 Student.Notes 并从数据库填充它的某些步骤?
最佳答案
您的类(class)学生和注释应该是公开的。
运行以下代码:
class Program {
static void Main(string[] args) {
using ( StudentDBContext efc = new StudentDBContext()) {
foreach (var v in efc.Students) {
Console.WriteLine("{0}", v.StudentName);
foreach (var vv in v.Notes) {
Console.WriteLine(" {0}", vv.Message);
}
}
}
}
}
public class Student {
public Student() {
//Notes = new List<Note>();
}
[Key]
public int StudentID {get; set;}
public virtual string StudentName {get; set;}
public virtual ICollection<Note> Notes {get; set;}
}
public class Note {
[Key]
public int NoteID {get; set;}
public int StudentID {get; set;}
public string Message {get; set;}
}
class StudentDBContext:DbContext {
public DbSet<Student> Students { get; set; }
public DbSet<Note> Notes { get; set; }
}
关于c# - Entity Framework 一对多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11365007/