LINQ到实体选择多对一对多的关系中的所有条目条目、实体、关系、LINQ

由网友(深知你是梦却不愿醒来i)分享简介:我有3个MySQL表:学生,类和 StudentsInClasses 。I have 3 MySql tables: Students, Classes and StudentsInClasses.实体框架转换到这些两个实体学生和类,每个链接到其他有多对一一对多导航属性(例如 Student.Classes )。...

我有3个MySQL表:学生 StudentsInClasses

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

实体框架转换到这些两个实体学生,每个链接到其他有多对一一对多导航属性(例如 Student.Classes )。

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).

但没有 StudentsInClasses 实体,因此什么叫最好的方法,使用LINQ到实体,SQL 等价的:

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;

我在寻找的{StudentId,CLASSID}对这样我就可以快速查找特定的学生是否在一个给定的类HashSet的(或同等学历)。 (什么是存储此的最佳方法是什么?)

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?)

非常感谢。

推荐答案

怎么样:

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);

(我怀疑查找比比较合适的HashSet 在这里。)

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

编辑:如果你不想使用查询EX pressions:

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 });
阅读全文

相关推荐

最新文章