实体框架多对多+计数

时间:2009-06-18 13:13:23

标签: c# linq entity-framework linq-to-entities

我有三张桌子,教授,教授学生,学生。

我想要所有教授+每位教授有多少学生。

我可以这样做:

context.ProfessorSet.Include("Student")

context.ProfessorSet.Include(“Student”)。ToList()将读取所有三个表。

但我不想得到学生桌,我希望Linq得到“教授表”+“伯爵(*)教授学生小组由StudentId”。

可能吗?

2 个答案:

答案 0 :(得分:2)

我使用这个:

        var c = from tag in contexto.ProfessorSet
                select new
                {
                    Tag = tag,
                    Count = tag.Student.Count
                };

但是生成这个SQL:

选择 C.Id, C.Nome, C.C1 从     (选择         援助,         A.Nome,         (选择             COUNT(0)             来自Dr.Studant AS B             在哪里A.Id = B.ProfessorId         )AS [C1]     来自AS A)教授

我想要这个:

从A教授中选择A.Id,Count(0) 内部加入教授学生B对A.Id = B.ProfessorId Group By A.Id

答案 1 :(得分:0)

from p in context.ProfessorSet
from s in p.Student
group s by s.StudentId into g
select new
{
    Professor = p,
    StudentCounts = from sc in g
                    select new
                    {
                        StudentId = sc.Key,
                        Count = sc.Group.Count()
                    }
}
相关问题