gpt4 book ai didi

linq - Entity Framework - System.IndexOutOfRangeException

转载 作者:行者123 更新时间:2023-12-02 22:28:40 24 4
gpt4 key购买 nike

我正在使用查询 SQL Server 2008 数据库的 Entity Framework 4.1。不幸的是,我们经常遇到以下异常:

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

实际示例代码:

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

更新**使用缓存更新了我的代码。

我用谷歌搜索找到并回答,但找不到根本原因的明确答案。一些遇到过这个问题的人可以分享解决方案吗。

谢谢。

最佳答案

调用 .Count() 执行查询。我不认为 .First() 会再次执行它,但也许是,并且在这些调用之间发生了一些变化。您可以尝试将查询重写为:

(from entity in result
where entity.employeeId == employeeID
select entity).FirstOrDefault() ?? new EmployeeEntity();

关于linq - Entity Framework - System.IndexOutOfRangeException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12600710/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com