JimBoone
JimBoone

Reputation: 554

Linq query for EF 4.1 data with nested lists

I'm working with WPF and EF 4.2 to build a desktop application. I have 3 entities which have cascading one-to-many relationships, Students have zero-or-more schools. Schools have zero-or-more classes attended. I need to display the data in a grouped list showing the student, all their schools then all their classes.

Students          School            Class
int Id            int Id            int Id
string Name       string Name       string Subject
int yearBorn      string Address    int Credits
IList<School>     IList<Class>

I'm stumped by how to shape the data.

The first issue is that EF 4.2 hides the Id of the entities in Navigation objects so I cannot use them as keys in a "group by".

The next issue is I'm not sure how to include the second level nesting in the groups since I also need to return attributes of objects along the way like Student.Name or School.Address.

Upvotes: 1

Views: 310

Answers (1)

Kirk Broadhurst
Kirk Broadhurst

Reputation: 28728

You shouldn't need to Group By - just retrieve the entities in their current object graph.

The standard is something like

var context = new EntityContext();
var students = context.Students.Include("Schools").Include("Schools.Classes");
return students;

This returns an objects graph containing a set of students, where each students contains a set of schools, where each school contains a set of classes. The 'grouping' is done by EF - this is the purpose of an ORM, which maps relational database tables into objects in your code.

Upvotes: 1

Related Questions