I have an application written using c# on the top of the ASP.NET MVC 5 and Entity Framework 6 using Database-First approach.
I have a Student
model, a ClassRoom
model and a relational model to link the two relations together called StudentToClassRoom
.
I want to be able to select all students and for each student I want to get all the ClassRoom
that the student has relation too.
Here are my models
public class Student
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<ClassRoom> ClassRoomRelations { get; set; }
}
public class StudentToClassRoom
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[ForeignKey("Student")]
[InverseProperty("Id")]
public int StudentId { get; set; }
[ForeignKey("ClassRoom")]
[InverseProperty("Id")]
public int ClassRoomId { get; set; }
public virtual Student Student { get; set; }
public virtual ClassRoom ClassRoom { get; set; }
}
public class ClassRoom
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Name { get; set; }
}
Here is what I tried
var students = DbContext.Students.Include(x => x.ClassRoomRelations)
.ToList();
However, that gives me the relation collection for each student. But I want to be able to get the ClassRoom
information for each student. So I want to create a Has-Many-Through between Student and ClassRoom. In the end results, I don't really care about the ClassRoomRelations
, I only care about the Student
and theClassRoom
objects.
How can I get a list of Student and a collection of all Class-Rooms for each student using Entity Framework?