C# &引用;当不存在数据时读取的尝试无效”;在查询结果上启动foreach循环时

C# &引用;当不存在数据时读取的尝试无效”;在查询结果上启动foreach循环时,c#,entity-framework,exception-handling,linq-to-entities,azure-sql-database,C#,Entity Framework,Exception Handling,Linq To Entities,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 {

我有一个疑问:

 // _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
 }
大多数情况下运行正常,但偶尔带有
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()

这没有任何意义。如何解决此问题?

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

有一些中等重量的活动,预计将在 几秒钟,但我想可能需要更长的时间。你认为暂停吗 发生了什么

我想象这是一个超时或类似的事情。您可以增加超时时间,也可以强制它进行计算,并将其存储在内存中以供以后处理。您可以通过在查询末尾添加
ToArray()
来完成此操作:

 var toProcess = (from jobItem in _db.Jobs
                 where jobItem.State == desiredState
                 select jobItem.ItemId).ToArray();

看看这是否有帮助。

这是一个非常奇怪的错误;看起来像某种内部混乱检查行;这是什么版本的.NET?@Marc Gravell:那是4.0版,EF是什么版本?4.0, 4.1, 4.2, 4.3? 您是否尝试过更新?随机问题;是否有人在您的连接上发出了
SET FMTONLY ON
SET ROWCOUNT[n]
?这看起来很奇怪,我只是想排除数据库中itemID为null的可能原因?