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
StudentandClassis called many to many relationship in EF terminology.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
OnModelCreatingappropriate to the relationships in your classes.Depending on your query needs you will find it informative to look at the following references: