带分组的实体框架查询(多对多)

发布于 07-11 10:21 字数 347 浏览 12 评论 0原文

我有一个经典的多对多场景,包含三个表(学生、课程和第三个学生课程作业表)。

我在新项目中使用 EF,并且 EF 设计器没有创建第三个表。 我需要选择所有课程以及分配给它的学生数量。 使用纯 SQL 非常简单:

select c.Id, c.Name, Count(sc.*) as StudentCount 
from Courses c left join StudentCourses sc on(c.Id=sc.CourseId)
group by c.Id, c.Name

但我不知道如何将此查询转换为 Linq to SQL。 请指教。

谢谢。

I have a classical many to many scenario with three tables (students, courses, and third StudentsCourses assignment table).

I'm using EF in my new project and EF designer doesn't create third table.
I need to select all cources along with number of students assigned to it.
Using plain SQL is very straightforward:

select c.Id, c.Name, Count(sc.*) as StudentCount 
from Courses c left join StudentCourses sc on(c.Id=sc.CourseId)
group by c.Id, c.Name

But I can't figure out how to translate this query to Linq to SQL.
Please advice.

Thank you.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

月隐月明月朦胧 2024-07-18 10:21:35

EF 设计器隐藏该表。 它仍然在那里,但它只是为您创建关联,因此您可以仅参考课程中的学生,反之亦然。

The EF designer hides the table. It's still there, but it just creates the assocation for you, so you can just reference students from courses or vice versa.

江城子 2024-07-18 10:21:35

您可以这样做:

var list = from c in context.Courses
           from s in c.Students
           select new
           {
             StudentName=s.Name,
             Class=s.Class,
           };

有关更多信息,请参阅 此页面

You could do something like this:

var list = from c in context.Courses
           from s in c.Students
           select new
           {
             StudentName=s.Name,
             Class=s.Class,
           };

for more information look at this page

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文