我正在使用 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 都已被处理。
谁能解释一下?