2

我在 aspx 页面上有一个控件中继器。我正在尝试将查询移出控件并进入父页面,因为每个控件的数据库都受到了巨大的打击。问题是我收到以下错误。

Cannot access a disposed object.
Object name: 'DataContext accessed after Dispose.'.

我不明白这一点,因为我认为执行 .ToList() 会强制执行查询

我在父页面中的代码

Private _activityList As IEnumerable(Of Activity)
Public ReadOnly Property ActivityList() As IEnumerable(Of Activity)
    Get
        Return _activityList
    End Get
End Property

Sub PopulatePage()
    Dim activityList = From a In dbContext.Activities Where a.PA.PA_Key.ToUpper().Trim() = "DCC" _
        Select a

    _activityList = activityList.AsEnumerable()
End Sub

我控制的代码是:

Public _activityList As List(Of Activity)
Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
    _activityList = CType(Me.Page, ParentPage).ActivityList.ToList()
End Sub

Sub grdSelectedActivities_NeedDataSource(ByVal source As Object, ByVal e As Telerik.WebControls.GridNeedDataSourceEventArgs) Handles grdSelectedActivities.NeedDataSource

    Dim lnqActivities = _activityList
    Dim objActivity As Activity = (From x In lnqActivities Where x.AC_Code = ActivityCode Select x).Single

    Dim lnqRoundActivities = (From roundactivity In objActivity.RoundActivities Where roundactivity.RA_DS_Code = DepartmentalSettingsCode 
                                  Select roundactivity Order By roundactivity.RA_Name)

    grdSelectedActivities.DataSource = lnqRoundActivities
End Sub

编辑

我认为这是失败的,因为它试图在grdSelectedActivities_NeedDataSource控制方法中获取 RoundActivities。因此我需要发送一个具有 RoundActivityies 子对象的活动对象。

我试图创建这个对象,但得到以下错误:

Explicit construction of entity type 'Activity' in query is not allowed.
enter code here

这是更新的代码:

 Dim activityList = (From a In dbContext.Activities Where a.PA.PA_Key.ToUpper().Trim() = "DCC" Select New Activity With {.AC_Code = a.AC_Code, .RoundActivities = a.RoundActivities})

解决方案:

我听从了@kristoferA 的建议并做了以下事情

Dim loadOptions = New DataLoadOptions()
loadOptions.LoadWith(Of Activity)(Function(a As Activity) a.RoundActivities)
loadOptions.AssociateWith(Of Activity)(Function(a As Activity) a.RoundActivities.Where(Function(z) If(z.RA_DS_Code = departmentCode, False)))
dataContext.LoadOptions = loadOptions
4

3 回答 3

1

听起来你很懒惰加载一些关联。

关闭延迟加载 (dc.DeferredLoadingEnabled = false),并将 DataLoadOptions 对象传递给 dc.LoadOptions 以指示 DC 您想要预先加载的内容。

于 2012-05-24T11:20:09.030 回答
0

请客 dbContext在 PopulatePage() 完成后得到处置,并且您的 Linq 选择返回类型是 IEnumerable(Of Activity) ,这只是一个准备好的 SQL 语句。

尝试..

_activityList = activityList.ToList()//.AsEnumerable()

编辑

如果您的模型是无状态的,您可以创建新的 dbContext 然后枚举并处理它。

Using db As New dbContext()

    Dim activityList = (From a In dbContext.Activities Where a.PA.PA_Key.ToUpper().Trim() = "DCC" _
    Select a).ToList()

    _activityList = activityList.ToList()
End Using
于 2012-05-24T11:01:22.293 回答
0

ai.farfa 对 ToList() 是正确的。那是触发实际查询的调用。我认为你应该在这条线上做:

 grdSelectedActivities.DataSource = lnqRoundActivities.ToList()
于 2012-05-24T11:07:12.700 回答