我必须上课:
public class Subject
{
[Key]
public int SubjectID { get; set; }
public string SubjectName { get; set; }
public virtual ICollection<Teacher> Teachers { get; set; }
}
和
public class Teacher
{
[Key]
public int TeacherID { get; set; }
public string TeacherName { get; set; }
public virtual ICollection<Subject> Subjects { get; set; }
}
所以我创建了两个表之间的多对多关系,EF将自动创建联结表:
SubjectTeachers:
PK SubjectID
PK TeacherID
我的问题是,如何告诉EF如何链接表中的值?
示例:
SubjectID = 1; SubjectName = Math;
SubjectID = 2; SubjectName =生物学;
TeacherID = 1; TeacherName = MathTeacher;
TeacherID = 2; TeacherName = MathTeacher2;
TeacherID = 3; TeacherName = BiologyTeacher;
如何在播种数据时在DbInitializer中指定我想将Match主题链接到数学教师?
编辑:种子方法
protected override void Seed(SchoolContext context)
{
GetTeachers().ForEach(t => context.Teachers.Add(t));
GetSubjects().ForEach(s => context.Subjects.Add(s));
}
private static List<Subject> GetSubjects()
{
var subjects = new List<Subject> {
new Subject
{
SubjectID = 1,
SubjectName = "Math"
},
new Subject
{
SubjectID = 2,
SubjectName = "Biology"
},
new Subject
{
SubjectID = 3,
SubjectName = "English"
},
};
return subjects;
}
private static List<Teacher> GetTeachers()
{
var teachers = new List<Teacher> {
new Teacher
{
TeacherID = 1,
TeacherName = "Math Teacher",
TeacherOffice = "A007",
},
new Teacher
{
TeacherID = 2,
TeacherName = "Math Teacher 2",
TeacherOffice = "A008",
},
new Teacher
{
TeacherID = 3,
TeacherName = "Biology Teacher",
TeacherOffice = "A009",
},
};
return teachers;
}