2016-01-29 46 views
3

我有兩個表之間的FK關係,但爲了這個查詢的目的,我需要得到每個FK的行數。返回2列,Id和計數,從EF作爲字典<int,int>

例如,我有一個CareTaker表與CareTakerId作爲PK;和Animal表格,其中CareTakerId作爲FK。鑑於CareTakerIds的列表,我希望每個護理人員負責的所有AnimalIds。事情是這樣的:

select CareTakerId, count(1) 
from Animal 
where CareTakerId in (1,2,3,4) 
    and AnimalTypeId = 3 
group by CareTakerId 

它返回

CareTakerId | No ColumnName 
1   | 42 
2   | 6 

我如何的EntityFramework做到這一點? 我需要這樣的結果,所以我想我會做它作爲一個Dictionary<int,int>Dictionary<CareTakerId,Count>) - 但我無法弄清楚如何寫EF查詢吧..這是我到目前爲止有:

query 
    .Where(r => r.AnimalTypeId == animalTypeId 
      && careTakerIds.Contains(r => r.CareTakerId)) 
    .GroupBy(r => r.CareTakerId) 
    // Not sure what to write here; r.CareTakerId doesn't exist 
    .Select(r => new {r.key, r.value }) 
    .ToDictionary(kvp => kvp.Key, kvp => kvp.value); 

如何在實體框架中選擇CareTakerId並計入(1)?

回答

2

你非常接近,只需添加「Count()」方法即可。

query 
    .Where(r => r.AnimalTypeId == animalTypeId 
      && careTakerIds.Contains(r => r.CareTakerId)) 
    .GroupBy(r => r.CareTakerId) 
    .Select(r => new {r.key, value = r.Count() }) 
    .ToDictionary(kvp => kvp.Key, kvp => kvp.value); 
5

Select這樣做:

//... 
//You have groups here, 
//so you can call Count extension method to get how many elements belong to the current group 
.Select(g => new {CareTakerId=g.Key,Count= g.Count() }) 
.ToDictionary(e=> e.CareTakerId,e=> e.Count); 
相關問題