Linq query for EF 4.1 data with nested lists

谁说胖子不能爱 提交于 2019-12-11 05:59:14

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/8111568/linq-query-for-ef-4-1-data-with-nested-lists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!