使用LINQ-to-SQL获取指定父节点列表的所有HierarchyID子节点
正确的LINQ-to-SQL写法
原SQL的核心逻辑是关联父表,筛选出父ID在指定列表中的所有子节点(含自身),你的LINQ代码存在两个关键错误:
- 关联条件错误使用了
child.HierarchyId.IsDescendantOf(child.HierarchyId),应该引用parent的HierarchyId - 不必要地使用
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
相关产品推荐
相关产品推荐

