是的 - 使用反射是确定查询所属的 DataContext 的唯一方法。触发查询时创建的数据对象也是如此。
以下内容并未严格回答 Rune 的问题,但如果您想使用反射来确定数据对象是否附加到数据上下文并由数据上下文监控,则可能会有所帮助:
以下代码定义了一个 Context 属性,该属性可以放置在数据对象上,然后用于返回该对象附加到的 DataContext(如果有)。
Private Const StandardChangeTrackerName As String = "System.Data.Linq.ChangeTracker+StandardChangeTracker"
Private _context As DataClasses1DataContext
Public Property Context() As DataClasses1DataContext
Get
Dim hasContext As Boolean = False
Dim myType As Type = Me.GetType()
Dim propertyChangingField As FieldInfo = myType.GetField("PropertyChangingEvent", BindingFlags.NonPublic Or BindingFlags.Instance)
Dim propertyChangingDelegate As PropertyChangingEventHandler = propertyChangingField.GetValue(Me)
Dim delegateType As Type = Nothing
For Each thisDelegate In propertyChangingDelegate.GetInvocationList()
delegateType = thisDelegate.Target.GetType()
If delegateType.FullName.Equals(StandardChangeTrackerName) Then
propertyChangingDelegate = thisDelegate
hasContext = True
Exit For
End If
Next
If hasContext Then
Dim targetField = propertyChangingDelegate.Target
Dim servicesField As FieldInfo = targetField.GetType().GetField("services", BindingFlags.NonPublic Or BindingFlags.Instance)
If servicesField IsNot Nothing Then
Dim servicesObject = servicesField.GetValue(targetField)
Dim contextField As FieldInfo = servicesObject.GetType.GetField("context", BindingFlags.NonPublic Or BindingFlags.Instance)
_context = contextField.GetValue(servicesObject)
End If
End If
Return _context
End Get
Set(ByVal value As DataClasses1DataContext)
_context = value
End Set
End Property
请注意,如果对象当前附加到已打开 ChangeTracking 的上下文,则该对象只能找到它的 DataContext。此属性依赖于 DataContext 已订阅对象的 OnPropertyChanging 事件以监视对象生命周期内的更改这一事实。
如果这有帮助,请给这篇文章投票。
有关使用反射查找事件处理程序的更多信息: