Skip to main content
 首页 » 编程设计

c#之如何从多对多关系中检索实体列表

2024年02月23日16oomusou

我正在尝试检索 List<Student>来 self 的数据库。

基本上,架构是:

GradeParalelo ---- GradeStudent ---- Student 

GradeStudent 表包含 GradeParalelo 和 Student 的主键。 注意: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。 这不是我想要的。

任何人都可以建议一种检索此集合的方法吗?

我想检索 GradeStudent 表中 GradeParalelo ID 为 6 的所有学生的图像。

基本上是这样,以更优雅的形式:

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; 
} 

请您参考如下方法:

怎么样

return db.GradeParaleloes.Single(g => g.GradeParaleloId == gradeParaleloId) 
                         .GradeStudents.Select(s => s.Student).ToList();