"Invalid attempt to read when there is no data" when starting the foreach loop on the query result

I have this query:

// _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 } 

which in most cases works fine, but from time to time a line with foreach will throw:

System.InvalidOperationException: Invalid read attempt when data is missing.

with the following stack trace:

 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() 

which makes no sense. How to resolve this?

+4
source share
1 answer

According to your answer to my comment:

There is medium-weight activity that is expected to be completed within a few seconds, but I think it might take longer. Do you think a timeout is going on?

I guess this is a timeout or something similar. You can increase the timeout , or simply force it to be evaluated and stored in memory for later processing. You can do this by adding ToArray() at the end of the query:

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

See if that helps.

0
source

Source: https://habr.com/ru/post/1412723/


All Articles