【问题标题】:An unhandled exception of type 'System.StackOverflowException' occurred in EntityFramework.dllEntityFramework.dll 中出现“System.StackOverflowException”类型的未处理异常
【发布时间】:2015-06-18 22:42:22
【问题描述】:

当我尝试使用 linq 查询大数据时,我遇到了异常(EntityFramework.dll 中发生了“System.StackOverflowException”类型的未处理异常)。引发错误的代码是,

    if (codeList != null && codeList.Count > 0)
        {
            List<string> codes = codeList.Select(x => x.DeptCode).Distinct().ToList();

            nameList = db.LegacyCodeDetails.Where(x => x.LegacyIdentifier.Contains(identifier) &&
                                                           x.ColumnAbr != null && x.ColumnAbr.Equals("NAME") &&
                                                           (codes.Where(y => x.LegacyIdentifier.Contains(y)).Count() > 0)
                                                    )
                                               .Select(x => new NameAndValue { Name = x.Value, Value = x.LegacyIdentifier }).Distinct().ToList();

            List<string> namesToDisplay = nameList.Select(x => x.Name).Distinct().ToList();

当有数百条记录时,相同的代码可以正常工作。我想知道可能是什么问题。

内部异常:无法计算表达式,因为当前线程处于堆栈溢出状态

环境:

Visual Studio 2012、Entity Framework 6.0、C#、SQL Server 2008 R2。

问题:

我是否对导致此异常的 linq 做错了什么?任何帮助表示赞赏。

【问题讨论】:

  • 在哪一行抛出异常?上面的例子中有很多 ToList() 都可能发生。
  • Stackoverflow - 是的,您将大量数据放入内存。没有 ToList 你能做到吗? ToList 将整个数据带入内存并在内存中进行过滤(linq to object)....但是如果您只有一个查询并且只执行一次列表。它可能会改善它
  • @DanHunex,感谢您的建议。我现在就试试。

标签: c# linq entity-framework


【解决方案1】:

我认为问题正在发生,因为 codes 太大,并且您将 IQueryable (db.LegacyCodeDetails.Where) 与 IEnumerable (codes) 混合在一起,因此生成的 SQL 将为 codes 中的每个项目包含一行.

如果codes 来自另一个表,您可以在查询中直接访问该表。例如:

替换:

codes.Where(y => x.LegacyIdentifier.Contains(y)).Count() > 0)

与:

db.Codes.Select(y => y.DeptCode).
        .Where(y => x.LegacyIdentifier.Contains(y)).Any())

【讨论】:

    猜你喜欢
    • 2016-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多