当使用Code First方法设置多对多关系时,默认情况下,连接表仅包含2列(2个表中的FK到PK)。
1)是否可能/如何设置包含一些其他字段的连接表,以及2)如何通过代码填充这些值?
例如:
class Student
{
public int Id { get; set; }
public string Name { get; set; }
public List<Course> Courses { get; set; }
}
class Course
{
public int Id { get; set; }
public string Name { get; set; }
public List<Student> Students { get; set; }
}
class MyDbContext : DbContext
{
public DbSet<Student> Students { get; set; }
public DbSet<Course> Courses { get; set; }
}
一个简单的数据库,包含具有多对多关系的学生和课程。但是,对于每个加入学生课程,我还需要一个字段,例如:PercentComplete,用于跟踪学生在每门课程中的距离。
如何实现这一目标?
由于
答案 0 :(得分:3)
这是与其他信息的多对多关系的案例。您需要创建一个名为Enrollments
的新实体。然后,您需要在学生 - 注册和课程 - 注册实体之间设置一对多关系。
public class Student
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public List<Enrollment> Enrollments { get; set; }//each student can have many enrollments
}
public class Course
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public List<Enrollment> Enrollments { get; set; }//each course can have many enrollments
}
public class Enrollment
{
public int EnrollmentId { get; set; }
public int PercentComplete{ get; set; }
public Course Course { get; set; } //each single enrollment involves one course
public Student Student { get; set; } //each single enrollment involves one student
}
您可以在此处找到详细示例:
https://practiceaspnet.wordpress.com/2015/11/09/many-to-many-relationships-with-additional-fields/