【问题标题】:IndexOutOfRangeException on Queryable.SingleQueryable.Single 上的 IndexOutOfRangeException
【发布时间】:2008-10-16 13:23:54
【问题描述】:

我有一个 ASP.NET 站点,该站点已经完美运行了很长时间,最近没有任何变化。从一个小时到下一个小时,我开始在执行如下 LINQ 查询的行中收到 IndexOutOfRangeException:

var form = SqlDB.GetTable<ORMB.Form, CDB>()
    .Where(f => f.FormID == formID)
    .Single();

ORMB.Form 是一个带有 LINQ to SQL 属性的 POCO 对象,将其映射到一个 MSSQL 表(映射被验证为正确)。堆栈跟踪如下:

System.Web.HttpUnhandledException: Exception of type 'System.Web.HttpUnhandledException' was thrown. ---> System.IndexOutOfRangeException: Index was outside the bounds of the array.
   at System.Collections.Generic.List`1.Add(T item)
   at System.Data.Linq.SqlClient.SqlConnectionManager.UseConnection(IConnectionUser user)
   at System.Data.Linq.SqlClient.SqlProvider.Execute(Expression query, QueryInfo queryInfo, IObjectReaderFactory factory, Object[] parentArgs, Object[] userArgs, ICompiledSubQuery[] subQueries, Object lastResult)
   at System.Data.Linq.SqlClient.SqlProvider.ExecuteAll(Expression query, QueryInfo[] queryInfos, IObjectReaderFactory factory, Object[] userArguments, ICompiledSubQuery[] subQueries)
   at System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider.Execute(Expression query)
   at System.Data.Linq.DataQuery`1.System.Linq.IQueryProvider.Execute[S](Expression expression)
   at System.Linq.Queryable.Single[TSource](IQueryable`1 source)
   at GetForm.Page_Load(Object sender, EventArgs e)

Reflecting System.Collections.Generic.List.Add 显示以下代码:

public void Add(T item)
{
    if (this._size == this._items.Length)
    {
        this.EnsureCapacity(this._size + 1);
    }
    this._items[this._size++] = item;
    this._version++;
}

应该容易出现 IndexOfOutRangeException 的唯一行是 this._items[this._size++] = item,但是我看不出我对此有何影响。

我可以通过应用程序域回收来解决问题,因此它必须以某种方式与缓存相关。在 DataContext 上关闭 ObjectTracking,以防万一。

我的直觉是这可能是一个线程问题,SqlConnectionManager 在名为“用户”的列表字段中缓存了 IConnectionUser。如果两个线程同时进入 Add 方法,是什么阻止了以下情况的发生:

T1: Add(x)
T2: Add(y)
T1: Since _size == _items.Length: EnsureCapacity(_size + 1)
T2: Since _size > _items.Length: _items[_size++] = item;
T1: _items[size++] = item <- OutOfRangeException since T2 didn't increase the capacity as needed

有人吗?

【问题讨论】:

    标签: c# linq


    【解决方案1】:

    您是否共享一个共同的 DataContext?这可以解释您所描述的线程问题,因为 DataContext 不是线程安全的。

    【讨论】:

      【解决方案2】:

      检查 dbml 中的所有“主键”列是否确实与数据库表上的主键相关。我刚刚遇到一种情况,设计人员决定在 dbml 中添加一个额外的 PK 列,这意味着 LINQ to SQL 在保存时无法找到外键的两边。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-06-22
        • 1970-01-01
        • 2012-06-11
        • 2012-01-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多