在查询结果上启动 foreach 循环时“不存在数据时尝试读取无效”

sha*_*oth 5 c# linq-to-entities entity-framework exception-handling azure-sql-database

我有这个查询:

 // _db derives from DbContext
 var toProcess = from jobItem in _db.Jobs
                 where jobItem.State == desiredState
                 select jobItem.ItemId;
 foreach (Guid itemId in toProcess ) //exception thrown on this line
 {
     // whatever
 }
Run Code Online (Sandbox Code Playgroud)

大多数情况下运行良好,但偶尔foreach会抛出:

System.InvalidOperationException:不存在数据时读取尝试无效

具有以下堆栈跟踪:

System.Data.SqlClient.SqlDataReader.ReadColumnHeader(Int32 i)
System.Data.SqlClient.SqlDataReader.IsDBNull(Int32 i)
System.Data.Common.Internal.Materialization.Shaper.ErrorHandlingValueReader`1.GetValue(DbDataReader reader, Int32 ordinal)
System.Data.Common.Internal.Materialization.Shaper.GetColumnValueWithErrorHandling[TColumn](Int32 ordinal)
System.Data.Common.Internal.Materialization.Coordinator`1.ReadNextElement(Shaper shaper)
System.Data.Common.Internal.Materialization.Shaper`1.SimpleEnumerator.MoveNext()
Run Code Online (Sandbox Code Playgroud)

这没有任何意义。我该如何解决?

yam*_*men 0

根据您对我的评论的回复:

有一些中等重量的活动预计会在几秒钟内完成,但我想可能需要更长的时间。您认为会发生超时吗?

我想这是超时或类似的事情。您可以增加超时,或者您可以强制它进行评估并存储在内存中以供以后处理。您可以通过ToArray()在查询末尾添加以下内容来完成此操作:

 var toProcess = (from jobItem in _db.Jobs
                 where jobItem.State == desiredState
                 select jobItem.ItemId).ToArray();
Run Code Online (Sandbox Code Playgroud)

看看是否有帮助。