如何在 Entity Framework 中设置自定义加入 table

How to setup custom join table in Entity Framework

使用 Code First 方法建立多对多关系时,默认情况下联接 table 仅包含 2 列(2 table 的 FK 到 PK)。

1) possible/How 我可以设置一个包含一些附加字段的连接 table 吗,以及 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,它跟踪学生在每门课程中的进度。

如何实现?

谢谢

这是具有附加信息的多对多关系的情况。您将需要创建一个名为 Enrollments 的新实体。然后,您需要在 Student - Enrollment 和 Course - Enrollment 实体之间设置一对多关系。

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/

https://practiceaspnet.wordpress.com/2015/11/13/displaying-related-entity-in-gridview-entity-framework-code-first/