[英]Adding Grouped Count to Linq Query
I have the following fields (obviously a simplified version of the actual domain) 我有以下字段(显然是实际域的简化版本)
MyEntity.ID,
MyEntity.Title,
MyEntity.ParentID,
MyEntity.RootID,
MyEntity.IsOpen
If an entity that has no parent spawns a child the ParentID is set as the ID of the parent entity and the RootID is set as the same. 如果没有父代的实体产生子代,则将ParentID设置为父代实体的ID,并将RootID设置为相同。 If that child then spawns a child then its child's parentID is it's direct parent's ID, but the Root is the ID of the eldest descendent, so: 如果那个孩子然后生一个孩子,那么它的孩子的parentID是它的直接父母的ID,而Root是最老的后代的ID,因此:
ID Title ParentID RootID IsOpen
1 One NULL NULL True
2 Two 1 1 False
3 Three 2 1 True
4 Four NULL NULL True
I want a query that will return the ID and Title of each entity, plus a Boolean that is True IF the entity is open AND there are any other Open entities that are related. 我想要一个查询,该查询将返回每个实体的ID和标题,以及一个布尔值,如果该实体处于打开状态并且有任何其他相关的Open实体,则返回True。
So For the above table Id expect to see 因此,对于上表Id希望看到的
ID Title IsOpenAndHasHasOpenRelations
1 One True
2 Two False
3 Three True
4 Four False
The IsOpenAndHasHasOpenRelations column could equally just be a count of the number of open relations IsOpenAndHasHasOpenRelations列同样可以只是打开关系数的计数
The logic is basically - Assuming entity is open, does it have a parent? 逻辑基本上是-假设实体是开放的,它是否有一个父实体? If not then are there any open entities that are its children? 如果不是,那么是否有任何开放实体为其子代? If it does have a parent are there any open entities that share to the same root? 如果确实有一个父级,是否有任何开放实体共享同一根?
I'm struggling to do this as a Linq to Entities Expression though. 我正在努力做到这一点,但是作为实体表达的Linq。 Can anyone help? 有人可以帮忙吗?
Edit. 编辑。 Here is the (slightly modified) current SQL that I'm attempting to move to LINQ: 这是我试图转移到LINQ的(略作修改的)当前SQL:
WITH PageIndex AS (
SELECT *
FROM EntityTable)
SELECT
[PageIndex].*
,CAST (CASE
WHEN EntityRecord.IsOpen = THEN 0
WHEN EntityRecord.[RootID] IS NOT NULL THEN
CASE
WHEN ( SELECT COUNT(ID) FROM EntityTable AS rootEntity
WHERE rootEntity.[ID] = PageIndex.[RootID]
AND (rootEntity.IsOpen = 1)
) > 0 THEN 1
ELSE 0
END
ELSE
CASE
WHEN ( SELECT COUNT(*) FROM EntityTable AS upissue
WHERE upissue.RootID = PageIndex.[ID]
AND (upissue.IsOpen = 1)
) > 0 THEN 1
ELSE 0
END
END AS BIT) AS IsMultipleLinkexEntitiesOpen
FROM PageIndex
The exact same logic in LinQ here: LinQ中的逻辑完全相同:
var res = DBcontext.EntityTable.Select(x => new
{
ID = x.ID,
Title = x.Title,
IsOpenAndHasHasOpenRelations = x.IsOpen ? false
: x.RootID != null ? DBcontext.EntityTable.Any(y => y.ID == x.RootID && y.IsOpen)
: (DBcontext.EntityTable.Any(y => y.ID == x.RootID && y.IsOpen))
});
It could become cleanier if you hav foreign keys your entity to it self. 如果您将自己的实体使用外键,它可能会变得更加干净。
I still could not understand your full logic, i just translate what i see in SQL. 我仍然无法理解您的完整逻辑,我只是翻译我在SQL中看到的内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.