Linq2SQL和递归树输出

时间:2014-07-31 09:18:23

标签: c# linq linq-to-sql

考虑一个类似树的结构,其中树只包含一个表 daTree ,字段为 intID intParentID 和< EM> strValue中。字段 intParentID 是可选的, null 值表示该条目是树的根(可能有很多)。

我希望Linq以SQL

的形式将所有条目返回给SQL
Root1
  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;发生了异常:

  

类型&#39; System.NotSupportedException&#39;的第一次机会异常发生了   在System.Data.Linq.dll中附加信息:方法   &#39; System.Collections.Generic.IEnumerable`1 [MyProject.daTree]   RecGetTree(MyProject.daTree,MyProject.DataContext)&#39;没有支持   转换为SQL。

您是否知道如何重写代码以使其工作?我正在使用VS 2013和.Net 4.5。

1 个答案:

答案 0 :(得分:1)

您可以提前强制评估LINQ表达式

IEnumerable<daTree> trees = context.daTrees
    .Where(t => t.intParent == parentID)
    .OrderBy(t => t.strName).ToList() // <-- here
    .SelectMany(t => RecGetTree(t, context));

它不会特别有效,但至少应该有效。

相关问题