在 Code First 中有很多方法可以表示多对多关系。这实际上仅取决于您对映射的需求。如果您只需要注册地图,那么到目前为止您所拥有的一切都有效。您显示的关系将被 Code First 识别,并且会自动为您创建一个名为“StudentClasses”的映射表
要在映射表中创建映射,只需执行以下操作:
using(var context = new StudentClassContext())
{
Student aStudent = new Student{ StudentName="Johnny", Class = new Class(){ ClassName="Gym"}}
context.Students.Add(aStudent);
context.SaveChanges();
}
您也可以反过来执行此操作:
using(var context = new StudentClassContext())
{
Class aClass = new Class{ ClassName = "Gym", Students = new Student(){ StudentName="Johnny"}}
context.Classes.Add(aClass);
context.SaveChanges();
}
如果您想更具体和明确地了解关系,可以在覆盖的上下文 OnModelCreating() 方法中设置显式映射。看起来像这样:
public class StudentClassContext
{
public DbSet<Student> Students { get; set; }
public DbSet<Class> Classes { get; set; }
public StudentClassContext()
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Student>()
.HasMany(aStudent => aStudent.Classes) // A student can have many classes
.WithMany(aClass => aClass.Students)); // Many classes can have many students
//.Map(c => c.ToTable("StudentClass); // Set the mapping table to this name
}
}
如果由于某种原因您需要在代码中或在 EntityFramework 上下文操作之外访问映射表,我会说创建一个专用的映射类并使其成为代码中的一等公民:
public class Student
{
//...
}
public class Class
{
//...
}
// New Map Class
public class StudentClassMapRecord
{
public int Id; // Map record PK
public Student Student { get; set; }
public Class Class { get; set; }
public StudentClassMapRecord(Student aStudent, Class aClass)
{
Student = aStudent;
Class = aClass;
}
//Uncomment below if you don't need property navigation
//public int StudentId { get; set; }
//public int ClassId { get; set; }
//public StudentClassMapRecord(int studentId, int classId)
//{
// StudentId = studentId;
// ClassId = classId;
//}
}