c# - Entity Framework 一对多

标签 c# asp.net-mvc-3 entity-framework

我正在使用 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/

相关文章:

c# - 在 listview-scroll 上加载数据

c# - 如何识别 HttpModule 中的 UNC Access

linq - 如何从 Entity Framework 导航属性创建 LINQ 表达式?

c# - Entity Framework 中异步方法的正确使用

asp.net-mvc - 如何在 asp.net mvc 3 中使用@html.actionlink 传递文本框值

c# - 防止对字符串上的数据库进行有害调用

c# - 在数据库更改时刷新实体

c# - 如何将 Expression<Func<T,bool>> 替换为 linq to sql 表达式的 where 子句

asp.net - 编译器错误消息 : CS0135: 'Model' conflicts with the declaration 'System.Web.Mvc.WebViewPage<TModel>.Model'

c# - 带下划线的 MVC 3 模型绑定(bind)