You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用LINQ-to-SQL获取指定父节点列表的所有HierarchyID子节点

正确的LINQ-to-SQL写法

原SQL的核心逻辑是关联父表,筛选出父ID在指定列表中的所有子节点(含自身),你的LINQ代码存在两个关键错误:

  1. 关联条件错误使用了child.HierarchyId.IsDescendantOf(child.HierarchyId),应该引用parent的HierarchyId
  2. 不必要地使用EF.Constant,直接用集合的Contains方法即可生成IN查询

写法1:贴近原SQL的Join结构

var entityIds =
    from child in Context.GlobalDocumentClassification
    join parent in Context.GlobalDocumentClassification
        on true equals true // 非等值关联,先做笛卡尔积再过滤
    where child.HierarchyId.IsDescendantOf(parent.HierarchyId)
        && documentClassificationIds.Contains(parent.Id)
    select child.Id;

写法2:更简洁的子查询风格

var entityIds =
    from child in Context.GlobalDocumentClassification
    where Context.GlobalDocumentClassification
        .Where(p => documentClassificationIds.Contains(p.Id))
        .Any(p => child.HierarchyId.IsDescendantOf(p.HierarchyId))
    select child.Id;

两种写法都会被EF正确转换为与原SQL逻辑一致的查询,第二种更符合LINQ的表达习惯,可读性更强。

内容的提问来源于stack exchange,提问作者Norbert Hüthmayr

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 04:01:05