chobo2
chobo2

Reputation: 85775

Many to Many Relationship with extra columns in EF 6 Code?

Say if I have the classic example of Student and Courses. A student can have many courses and course can have many students.

How do I make the middle table in EF 6 code if I wanted to add an extra field on the many table part?

Do I just make in code another class and then hook it up somehow?

DB Context

public class MyContext : DbContext
{
    public MyContext (string nameOrConnectionString) : base(nameOrConnectionString)
    {
        // this.Configuration.ProxyCreationEnabled = false;
        Database.SetInitializer(new CreateDatabaseIfNotExists<OSPContext>());
    }

    public DbSet<Student> Students { get; set; }
    public DbSet<Course> Courses { get; set; }

    public DbSet<StudentCourse> StudentCourses { get; set; }

}


public class StudentCourse
{
    [Key]
    public Guid StudentCourseId { get; set; }

    public Guid StudentId { get; set; }

    [ForeignKey("StudentId")]
    public virtual Student Student { get; set; } // Include this so you can access it later

    public Guid CourseId { get; set; }

    [ForeignKey("CourseId")]
    public virtual Course Course { get; set; }

    public int Permissions { get; set; }
}

public class Course
{
    [Key]
    public  Guid Id { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Student> Students { get; set; } = new >();
}

public class Student
{
    [Key]
    public  Guid Id { get; set; }
    public  string Email { get; set; }
    public virtual ICollection<Course> Courses { get; set; } = new List<Course>();

}

Upvotes: 0

Views: 3799

Answers (1)

David Lee
David Lee

Reputation: 2100

Given you are code first I would do something like the following.

public class Student
{
    [Key]
    public int StudentId { get; set; }
    public string Name { get; set; }

    public List<StudentCourse> Courses { get; set; } // So you can access Courses for a student
}

public class Course
{
    [Key]
    public int CourseId { get; set; }
    public string Name { get; set; }

    public List<StudentCourse> Students { get; set; }
}

public class StudentCourse
{
    [Key]
    public int StudentCourseId { get; set; }

    public int StudentId { get; set; }
    [ForeignKey("StudentId")]
    public Student Student { get; set; } // Include this so you can access it later

    public int CourseId { get; set; }        
    [ForeignKey("CourseId")]
    public Course Course { get; set; } 
}

EDIT: Wanted to note relationships are established with Data Attributes, you could also use EF Fluent API to establish your relationships. The properties will look the same, but without the [ForeignKey("")]

Upvotes: 6

Related Questions