简体   繁体   中英

Using Entity Framework how can I retrieve a collection from a table?

Here are the tables:

在此输入图像描述

I need to retrieve a collection of Student objects, so I can access their names, last names, etc.

I'm kind of stuck so any help is very welcome, I'm always trying to learn and apply new things to make them stick. :)

So far, I've tried this:

private void cmbGradeParalelo_SelectedIndexChanged(object sender, EventArgs e)
{
    int gradeParaleloId = Convert.ToInt32(cmbGradeParalelo.SelectedValue);

    using (StudentRepository studentRepo = new StudentRepository())
    {
        studentRepo.FindAllStudents().Where(s => s.GradeStudents
    }
}

.GradeStudents is an EntityCollection<GradeStudent> so I think I can query the data using Linq, but I don't know how. I've never done something like this. :)

Thank you for your time!

Yes, you can query with Linq. There is one beginner caveat, though, that being the need for Include:

Context.Students
       .Include("GradeStudents")
       .Include("GradeStudents.GradeParalelo")
       .First<Student>(s => s.StudentId == 1)
       .GradeStudents

etc.

If you provide a little more information on what you are trying to do, I might be more help.

Note also that if your join table (GradeStudents) did not have extra columns, it would be an Assocation, and you would have access to GradeParalelo directly from Student.

You may find one of these tutorials helpful, depending on whether you're using MVC or Web Forms

MVC / Code First http://www.asp.net/entity-framework/tutorials/reading-related-data-with-the-entity-framework-in-an-asp-net-mvc-application

Web Forms / Database First http://www.asp.net/entity-framework/tutorials/the-entity-framework-and-aspnet- –-getting-started-part-4

if your tying to get all Students with at least one GradeParalelo then that would work

studentRepo.FindAllStudents()
    .Where(s => s.GradeStudents.Any(gs => gs.GradeParaleloId == gradeParaleloId));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM