我有兩個表之間的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)?