问题描述
我有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 });
这篇关于LINQ到实体选择多对一对多的关系中的所有条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!