2

我正在使用实体框架并具有以下类

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 并从数据库中填充它的一些步骤?

4

3 回答 3

3

你的班级学生和笔记应该是公开的。

以下代码运行:

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; }        
}
于 2012-07-06T16:01:59.080 回答
1

尝试这个:

using (StudentDBContext a = new StudentDBContext())
{
   var b = ((from c in a.Student
           join b in a.Notes on b.StudentId equals c.StudentId into sNotes
                 from notes in sNotes.DefaultIfEmpty()
           where c.StudentId==1001
           select c).SingleOrDefault();
   if (b != null )
     ...
}

请注意,Entity Framework 将对您的数据进行延迟加载。因此,如果您不做一些事情来填充它,那么您将不会得到它。还有其他方法可以做到这一点,但除此之外,此查询清楚地记录了您既想要学生也想要笔记。

于 2012-07-06T15:53:41.933 回答
0

这不应该是虚拟的。

public virtual NoteID {get; set;} 

它应该是一个整数:

public int NoteID {get; set;}
于 2012-07-06T15:43:39.007 回答