0

我正在使用 VB.Net。我已经解决了代码返回错误“无法访问已处理的对象。对象名称:'DataContext 在 Dispose 之后访问。'”的行为。我的问题:我根本不明白它为什么起作用!这是我发生错误时的代码:

Public Function Element_Import(ByVal id_element As Integer) As elements

    Using db As New GlobalDataContext(MyConnexion)

        Return (From element In db.elements
                Select element
                Where element.id_element = id_element).First
    End Using

End Function

然后我尝试重新获取数据:

Dim myElement As elements = _MyConnection.Element_Import(id_element)
Dim myLocal As List(Of elements_localisation) = myElement.elements_localisation.ToList '-- ObjectDisposedException !

当我导入我的元素然后尝试访问名为“elements_localisation”和“elements_files”的子表时,会发生 ObjectDisposedException。这是公平的,因为 DataContext 不可用。

所以我做了一些不同的事情:

 Public Function Element_ImportContext(ByVal id_element As Integer) As elements
    Dim myElement As elements
    Dim myElementLocalisation As New List(Of elements_localisation)
    Dim myElementFiles As New List(Of elements_files)
    Using db As New GlobalDataContext(MyConnexion)
        myElement = (From element In db.elements
                Select element
                Where element.id_element = id_element).First

        myElementLocalisation = myElement.elements_localisation.ToList
        myElementFiles = myElement.elements_files.ToList
    End Using
    Return myElement

End Function

然后我尝试重新获取数据:

Dim myElement As elements = _MyConnection.Element_ImportContext(id_element)
Dim myLocal As List(Of elements_localisation) = myElement.elements_localisation.ToList '-- IT WORKS !

我真的很想了解发生了什么,因为在这两种情况下,DataContext 都已被处理。

谁能解释一下?

4

1 回答 1

1

When you write LINQ, you write a query to be executed against some data, that query is only executed when another part of the code needs the data.

In your case, you are returning the myElement variable because you have used .First(), which forces the query to be executed and the first item to be returned.

The properties elements_localisation and elements_files are likely to be virtual properties that are only loaded when you request them. (This is certainly the case with Entity Framework, I'm not sure what you're using here).

Your program will try to access the virtual property which will then go off to the data context to get the next bit of data you requested, but in your case the data context is disposed.

Your second approach works because you have used ToList() on the virtual properties, which forces the data to be retrieved then and there, before your data context has been disposed.

于 2013-09-11T10:12:58.473 回答