如何从EntityCollection中过滤特定信息?

时间:2011-05-11 02:23:15

标签: c# .net linq entity-framework-4

我想在results变量中显示每个学生的成绩信息。

我的数据库设置方式是:

Grade --- GradeStudent --- Student

因此,每个不同的年份,我都会​​有一个独特的GradeStudent记录,其中包含成绩ID,学生ID以及该记录的年份。

我使用Entity Framework 4作为我的ORM,我想在dataGridView中为每个学生显示成绩名称。

private void btnSearch_Click(object sender, EventArgs e)
{
    StudentRepository repo = new StudentRepository();
    var results =
        repo.FindAllStudents().Where(
            s =>
            s.Name == txtSearchQuery.Text || 
            s.LastNameFather == txtSearchQuery.Text ||
            s.LastNameMother == txtSearchQuery.Text);

    dataGridView1.DataSource = results.Select(s => new
    {
        Codigo = s.StudentId,
        Nombre = s.LastNameFather + " " + s.LastNameMother + ", " + s.Name,
        Sexo = s.Sex,
        Telefono = s.Telephone
    }).ToList();
}

如果我尝试执行以下操作,我只能调用EntityCollection集合,因为可能有许多与我的学生关联的GradeStudent对象。每年一个。

所以我需要获得他在X年期间的成绩。

你对如何做到这一点有什么建议吗?

2 个答案:

答案 0 :(得分:0)

如果我理解了这个问题 - 您希望获得Grade对象(通过GradeStudent中间表)。如果是这种情况,您需要在EF模型中创建一个NavigationProperty,以将Grade与GradeStudent(* - 1)和GradeStudent与Student(0..1 - *)相关联。

至于将数据提取到您的上下文中,这是一个使用RIA的Silverlight应用程序吗?如果是这样,您的服务中的GetStudentsQuery方法将需要包含这些实体,以便与您的Student对象一起返回数据。

答案 1 :(得分:0)

如果grade已知,则应该有效:

StudentRepository repo = new StudentRepository();
var results =
    repo.FindAllStudents().Where(
        s =>
        (s.Name == txtSearchQuery.Text || 
        s.LastNameFather == txtSearchQuery.Text ||
        s.LastNameMother == txtSearchQuery.Text) &&
        s.GradeStudent.Any(gs => gs.Grade = grade));
相关问题