Linq2SQL和重复树输出
本文关键字:输出 Linq2SQL | 更新日期: 2023-09-27 18:15:57
考虑一个树状结构,其中树只包含一个表daTree,字段为intID, intParentID和strValue。字段intParentID是可选的,null值表示该条目是树的根(可能有很多)。
我希望Linq以
的形式将所有条目返回给SQLRoot1
Root1-Child1
Root1-Child2
Root1-Child2-Child1
...
Root2
,因此编写了以下枚举数
IEnumerable<daTree> RecGetTree(daTree tree, DataContext context) {
int? parentID = null;
if (tree != null) {
parentID = tree.intID;
yield return tree; //emit current tree
}
IEnumerable<daTree> trees = context.daTrees
.Where(t => t.intParent == parentID)
.OrderBy(t => t.strName)
.SelectMany(t => RecGetTree(t, context));
foreach(var child in trees)
yield return child;
}
,最初使用null和Linq2SQL数据上下文调用。
我的问题是,一个异常发生在yield return child;
:
类型为"System"的第一次机会异常。NotSupportedException"由于发生附加信息:方法"System.Collections.Generic.IEnumerable"1 (MyProject.daTree)RecGetTree (MyProject的。数据树,MyProject.DataContext)'不支持翻译成SQL
你知道我怎样重写代码才能使它工作吗?我使用的是VS 2013和。net 4.5。
可以提前强制LINQ表达式求值
IEnumerable<daTree> trees = context.daTrees
.Where(t => t.intParent == parentID)
.OrderBy(t => t.strName).ToList() // <-- here
.SelectMany(t => RecGetTree(t, context));
它不会特别有效,但至少应该可以工作。