我试图从我的数据库中检索List<Student>
。如何从多对多关系中检索实体列表?
基本上,该架构是:
GradeParalelo ---- GradeStudent ---- Student
凡GradeStudent表适用于GradeParalelo和学生的主键。 注意:GradeStudent表有一个额外的列来保存一个整数。这不仅仅是一个关联表。
这里是我试过到目前为止:
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();
}
但它检索每一个gradeParalelo我选择一个学生。可以理解,因为我将一个StudentId与一个GradeParaleloId进行比较。 这不是我想要的。
任何人都可以提出一种方法来检索这个集合吗?
形象地说,我希望检索在与GradeParalelo ID 6
基本上这一点,GradeStudent表中的所有学生在一个更优雅的形式:
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;
}
我似乎无法调用.SelectMany方法,为什么? – 2011-04-11 13:53:20
这似乎是完全错误的。单返回IQueryable和SelectMany仅适用于IEnumerable。 – 2011-04-11 14:01:01
@Sergio:我的错。它现在应该工作。 – SLaks 2011-04-11 14:14:07