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; }
}
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With