Entity Framework - System.IndexOutOfRangeException

梦想的初衷 提交于 2019-12-11 09:43:40

问题


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.


回答1:


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



回答2:


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




回答3:


Try to return like this:

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


来源:https://stackoverflow.com/questions/12600710/entity-framework-system-indexoutofrangeexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!