2009-06-18 25 views
1

我有三張表格,教授,教授,學生,學生。實體框架多對多+數量

我想要所有的教授+每位教授有多少名學生。

我可以做到這一點。

context.ProfessorSet.Include("Student") 

context.ProfessorSet.Include( 「學生」)ToList()將讀取所有三個表。

但我不想得到學生表,我希望Linq只是得到「教授表」+「計數(*)教授學生組由StudentId」。

它有可能嗎?

回答

2

我使用這個:

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

但生成該SQL:

選擇 C.Id, C.Nome, C.C1 FROM (SELECT 一.Id, A.Nome, (SELECT COUNT(0) FROM ProfessorStudant A SB WHERE A.Id = B.ProfessorId )AS [C1] FROM的教授)

我想這樣的:

選擇A.Id,COUNT(0)從A教授 內部聯接ProfessorStudent B關於上線 教授= p A.Id = B.ProfessorId 集團通過A.Id

+0

謝謝@Fujiy它對我來說非常完美! – 2016-05-17 14:23:08

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() 
        } 
} 
+0

錯誤, 無法解析符號p 和COUNT = sc.Count() Count()不存在 – 2009-06-19 12:49:05

+0

固定計數。 p是正確的。 – 2009-06-19 13:24:27