Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to represent Bridge table in Entity Framework Code First

I am trying to find out how I can represent a bridge table between two entities (many to many relation) I'm Using Entity Framework Code First

Student:
   StudentID int  PK
   StudentName VARCHAR(50)

Class:
   ClassID int PK
   ClassName VARCHAR(50)

StudentClass:
   StudentID INT PK
   ClassID INT PK

What is the best Class Structure should i Use to represent it in Entity Framework Code First and how can i select from the bridge table and insert in it.

Should I represent the classes it like this:

    public class Student
    {
        public int StudentId { get; set; }
        public string StudentName { get; set; }

        public List<Class> Class { get; set; }

    }


    public class Class
    {
        public int ClassId { get; set; }
        public string ClassName { get; set; }

        public List<Student> Students { get; set; }
    }
like image 741
Amr Ramadan Avatar asked Jan 03 '13 23:01

Amr Ramadan


1 Answers

In short: This relationship type between Student and Class is called many to many relationship in EF terminology.

Entity framework handles tables participating in Many to Many relationship in a nice manner. If the junction table (sometimes called bridge table, association table, link table, etc) only consists of the foreign keys and no other columns, then that table is abstracted by EF and the two sides get a navigational property exposing a collection of the other side.

What you would need is to generate a Entity Model for the above tables first or define your code first structure like in the following post - Creating a Many To Many Mapping Using Code First.

Basically, depending on your structure you need to set the method OnModelCreating appropriate to the relationships in your classes.

protected override void OnModelCreating(DbModelBuilder modelBuilder)

Depending on your query needs you will find it informative to look at the following references:

  • Queries involving many to many relationship tables
  • Many To Many Mappings in Entity Framework
  • Many-to-Many Relationships with Entity Framework
like image 154
Yusubov Avatar answered Oct 22 '22 22:10

Yusubov