Loc*_*rde 3 c# linq-to-entities entity-framework
我在两个表之间有一个FK关系,但是为了这个查询的目的,我需要得到每个FK的行数.
例如,我有一个CareTaker表CareTakerId作为PK; 还有一张FK 的Animal表格CareTakerId.给出一个列表CareTakerIds,我想要每个看护者负责的所有AnimalIds.像这样的东西:
select CareTakerId, count(1)
from Animal
where CareTakerId in (1,2,3,4)
and AnimalTypeId = 3
group by CareTakerId
Run Code Online (Sandbox Code Playgroud)
哪个回报
CareTakerId | No ColumnName
1 | 42
2 | 6
Run Code Online (Sandbox Code Playgroud)
我如何在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);
Run Code Online (Sandbox Code Playgroud)
如何CareTakerId在实体框架中选择和计算(1)?
在你的这个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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
116 次 |
| 最近记录: |