2014-05-07 22 views
0

我有兩個類,Profile和Download。下載具有映射到配置文件中ID的外鍵ProfileID。下載中的每一行代表連接的配置文件的一個下載。Linq通過在另一個列表中出現外鍵來查詢命令列表

我在製作一個linq查詢時遇到了麻煩,該查詢獲取已下載多少次的訂單配置文件列表。編輯: 這是我迄今爲止在功能。

IndexViewModel model = new IndexViewModel(); 
    model.NewSubtitles = (from Profile in _ProfileRepo.GetAll() 
         orderby Profile.ID descending 
         select Profile).Take(5).ToList(); 

    // This doesn't work: 
    // model.TopSubtitles = (from n in _ProfileRepo.GetAll() 
    //      join d in _DownloadRepo.GetAll() on n.ID equals d.ProfileID into c 
    //      group c by c.ProfileID into g 
    //      orderby g.Count() descending 
    //      select n).Take(5).ToList(); 

     return View(model); 
+2

你有什麼代碼已經準備好,我們可以有一看? – DDiVita

+0

我將它添加到原始帖子中。 – granra

回答

1

試試這個:

 model.NewSubtitles = (from Profile in _ProfileRepo.GetAll() 
        join downloads in _DownloadRepo.GetAll() on Profile.UserId equals downloads.UserId 
       group downloads by Profile into p 
        orderby p.Count() descending 
        select new {p.Key.UserId , p.Key.UserName , p.Count()).Take(5).ToList(); 
+1

這很有幫助,謝謝! :) – granra

0

你有沒有嘗試過這樣的:

from d in Downloads 
orderby d.Profiles.Count() 
... 

0

應該做你想要什麼:

model.TopSubtitles = (from p in _ProfileRepo.GetAll() 
         join d in _DownloadRepo.GetAll() on p.ID equals d.ProfileId 
         group d by p into g 
         orderby g.Count() descending 
         select g.Key).Take(5).ToList(); 

和挑戰LINQ語法:

model.TopSubtitles = _ProfileRepo.GetAll() 
    .Join(_DownloadRepo.GetAll(), p => p.ID, d => d.ProfileId, (p, d) => new { Profile = p, Download = d }) 
    .GroupBy(x => x.Profile) 
    .OrderByDescending(g => g.Count()) 
    .Select (g => g.Key) 
    .Take(5) 
    .ToList(); 
相關問題