LINQ to Entities select all entries in many-to-many relationship

你。 提交于 2019-12-19 11:39:13

问题


I have 3 MySql tables: Students, Classes and StudentsInClasses.

The Entity Framework translates these into two entities Student and Class, each linking to the other with a many-to-many navigation property (e.g. Student.Classes).

But there is no StudentsInClasses entity, so what's the best way to call, using LINQ to Entities, the equivalent of SQL:

SELECT StudentId, ClassId FROM StudentsInClasses;

I'm looking for a HashSet (or equivalent) of { StudentId, ClassId } pairs so I can quickly look up whether a given student is in a given class. (What's the best way of storing this?)

Many thanks.


回答1:


How about:

var query = from @class in db.Classes
            from student in @class.Students
            select new { ClassId = @class.ID, Student = student };

var lookup = query.ToLookup(x => x.ClassId,
                            x => x.Student);

(I suspect a Lookup is more appropriate than a HashSet here.)

EDIT: If you don't want to use query expressions:

var query = db.Classes
              .SelectMany(@class => @class.Students,
                          (@class, student) => new { ClassId = @class.ID,
                                                     Student = student });


来源:https://stackoverflow.com/questions/7800332/linq-to-entities-select-all-entries-in-many-to-many-relationship

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