[英]How can I retrieve a List of entities from a many to many relationship?
I'm trying to retrieve a List<Student>
from my database. 我正在尝试从我的数据库中检索List<Student>
。
Basically, the schema is: 基本上,架构是:
GradeParalelo ---- GradeStudent ---- Student
Where the GradeStudent table holds primary keys for GradeParalelo and Student. GradeStudent表包含GradeParalelo和Student的主键。 NOTE: The GradeStudent table has an extra column to hold an integer. 注意:GradeStudent表有一个额外的列来保存整数。 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. 可以理解,因为我正在将StudentId与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. 我想要使用GradeParalelo ID 6检索GradeStudent表中所有学生的图像。
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;
}
How about 怎么样
return db.GradeParaleloes.Single(g => g.GradeParaleloId == gradeParaleloId)
.GradeStudents.Select(s => s.Student).ToList();
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. 如果你有正确的FK,你只需要调用FK,在内部它将链接所有需要的表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.