How to setup custom join table in Entity Framework

北城余情 提交于 2019-12-10 11:49:44

问题


When setting up a many-to-many relationship with Code First approach, by default the join table only includes 2 columns (FK to PK of the 2 tables).

1) Is it possible/How can I setup a join table that will include some additional fields, and 2) how do I fill these values via code?

For example:

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; }
}

A simple db with Students and Courses with a many-to-many relationship. However for each join Student-Course, I also want a field, for example: PercentComplete, that tracks how far a student is in each course.

How can this be achieved?

Thanks


回答1:


This is a case for many-to-many relationship with additional information. You will need to create a new entity called, let's say Enrollments. Then, you will need to set 1-to-Many relationships between Student - Enrollment and Course - Enrollment entities.

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
}

You can find a detailed example here:

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/



来源:https://stackoverflow.com/questions/29966939/how-to-setup-custom-join-table-in-entity-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!