gpt4 book ai didi

c# - Entity Framework 一对多

转载 作者:行者123 更新时间:2023-11-30 21:06:07 25 4
gpt4 key购买 nike

我正在使用 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 总是空的。我是否遗漏了初始化 Student.Notes 并从数据库中填充它的某些步骤?

最佳答案

你的类(class) Student 和 Note 应该是公开的。

运行以下代码:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com