2

I'm using entity framework 4.1 which queries a SQL Server 2008 database. Unfortunately every often we get the exception below:

<ExceptionType>System.IndexOutOfRangeException, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</ExceptionType>
  <Message>Index was outside the bounds of the array.</Message>



at System.Data.SqlClient.SqlDataReader.ReadColumnHeader(Int32 i)
   at System.Data.SqlClient.SqlDataReader.IsDBNull(Int32 i)
   at System.Data.Common.Internal.Materialization.Shaper.ErrorHandlingValueReader`1.GetValue(DbDataReader reader, Int32 ordinal)
   at System.Data.Common.Internal.Materialization.Shaper.GetPropertyValueWithErrorHandling[TProperty](Int32 ordinal, String propertyName, String typeName)
   at lambda_method(Closure , Shaper )
   at System.Data.Common.Internal.Materialization.Shaper.HandleEntityAppendOnly[TEntity](Func`2 constructEntityDelegate, EntityKey entityKey, EntitySet entitySet)
   at lambda_method(Closure , Shaper )
   at System.Data.Common.Internal.Materialization.Coordinator`1.ReadNextElement(Shaper shaper)
   at System.Data.Common.Internal.Materialization.Shaper`1.SimpleEnumerator.MoveNext()
   at System.Linq.Enumerable.First[TSource](IEnumerable`1 source)
   at System.Linq.Queryable.First[TSource](IQueryable`1 source)
   at OnlineSelfService.Business.ContentServiceBusiness.GetPageContent(Int32 pageId)</StackTrace>

The actual sample code:

//Caller
  public EmployeeEntity GetEmployeeDetail(int employeeID)
    {
         IQueryable<Employee> result=null;
         if (myCaching.Contains("Employee"))
            {
                result = (IQueryable<Employee>)myCaching["Employee"];
            }
            else
            {
                result = dataAccess.GetEmployeeDetail();
                myCaching.AddToCache("Employee", result); //Expire in 2min
            }

            IQueryable<Employee> entityResult = from entity in result
                                                         where entity.employeeId == employeeID
                                                         select entity;
       if (entityResult.Count<Employee>() > 0)
                return entityResult.First<Employee>();
            return new EmployeeEntity();
   }

}

//DAL
public IQueryable<Employee> GetEmployeeDetail()
{
    DatabaseEntities ent = new DatabaseEntities(this._connectionString);
    IQueryable<Employee> result = from employee in ent.EmployeeEntity
                                           select employee;

    return result;
}

UPDATE** Updated my code with caching.

I googled to find and answer but could not find a definitive answer the root cause. Could some who have faced this issue share a resolution.

Thank you.

6
  • Is your context out of sync with the database? (Database columns do not match class properties?) Sep 26, 2012 at 17:45
  • Issue only occurs randomly and I don't suspect it's a sync issue.
    – Nil Pun
    Sep 26, 2012 at 23:31
  • The link you provided doesn't have answer marked as accepted.
    – Nil Pun
    Sep 28, 2012 at 21:44
  • No, but since the exceptions and circumstances are so similar it is useful to cross-link the questions. Sep 28, 2012 at 21:47

3 Answers 3

5

Calling .Count() executes the query. I wouldn't think the .First() would execute it again but maybe it is, and something has changed in between these calls. You could try rewriting the query as:

(from entity in result
where entity.employeeId == employeeID
select entity).FirstOrDefault() ?? new EmployeeEntity();
3
  • I've updated the code above with caching. Could that cause it?
    – Nil Pun
    Sep 26, 2012 at 21:31
  • @dskh Nice catch, it IS reexecuting the query, count do not fetch the data, it just performs an SQL COUNT, FirstOrDefault looks like the right solution here Oct 1, 2012 at 15:15
  • @Guillaume86, thanks for your answer what is IS stands for why count would not fetch data?
    – Nil Pun
    Oct 1, 2012 at 22:07
0

Any function called on IEnumerable or IQueryable will re-execute the query... which is why it's not good to put things like that in loops. You end of up tons of queries to the DB. As for why it's getting the Exception I would use .Any() instead of count to determine the length of the result

return (entityResult.Any<Employee>() > 0) ? entityResult.First<Employee>() : new EmployeeEntity();

Although the logic is a bit confusing, because you want to return a single EmployeeEntity and the query suggest you are expecting only one back. So you could just use

entityResult.Single<Employee>() 

which will throw an exception if more than one is returned unless you can't handle exceptions in the caller. Then SingleOrDefault might be best then just check for null and not have a count or any check at all.

Just some suggestions there is always more than one way to do something

0

Try to return like this:

return entityResult.First(e => e.employeeId == employeeID);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.