Reputation: 36743
I'm trying to retrieve a List<Student>
from my database.
Basically, the schema is:
GradeParalelo ---- GradeStudent ---- Student
Where the GradeStudent table holds primary keys for GradeParalelo and Student. NOTE: The GradeStudent table has an extra column to hold an integer. This is not just an association table.
Here's what I've tried so far:
ColegioDBV2Entities db = new ColegioDBV2Entities();
public List<Student> FindAllStudentsFromGradeParalelo(int gradeParaleloId)
{
return (db.Students
.Include("GradeStudents")
.Include("GradeStudents.GradeParalelo")
.Where<Student>(s => s.StudentId == gradeParaleloId)).ToList();
}
But it's retrieving a single student for every gradeParalelo I choose. Understandably, because I'm comparing a StudentId with a GradeParaleloId. This is not what I want.
Can anyone suggest a way to retrieve this collection?
Image that I want to retrieve all students that are in the GradeStudent table with GradeParalelo ID 6.
Basically this, in a more elegant form:
public List<Student> FindAllStudentsFromGradeParalelo(int gradeParaleloId)
{
List<Student> students = new List<Student>();
using(GradeStudentRepository repo = new GradeStudentRepository())
{
var items = repo.FindAllGradeStudents().Where(g => g.GradeParaleloId == gradeParaleloId);
StudentRepository studentRepo = new StudentRepository();
foreach (var o in items)
{
students.Add(studentRepo.FindStudent(o.StudentId));
}
}
return students;
}
Upvotes: 1
Views: 124
Reputation: 887453
How about
return db.GradeParaleloes.Single(g => g.GradeParaleloId == gradeParaleloId)
.GradeStudents.Select(s => s.Student).ToList();
Upvotes: 3
Reputation: 75083
that is a simple query as:
return
db.Students
.Where( x => x.GradeParalelo.gradeParaleloId == gradeParaleloId )
.ToList();
if you have the FK right, you just need to call the FK and internally it will link all the needed tables.
Upvotes: 1