You can achieve this by using reflection, figuring out if the PropertyChanging event has been connected, but consider how to hack it, and perhaps you can avoid using it with a better design. Our use case is to delegate detach_EntityName, where we change the default Linq behavior only by deleting the foreign record key (setting it to null), with the actual removal from the database.
public static DataContext GetDataContextFromEntityObject(object entity) { // Use a reflection to get the invocaiton list. var o = (PropertyChangingEventHandler)entity.GetType().GetField("PropertyChanging", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(entity); var o = GetFieldValue(entity, "PropertyChanging"); if (o == null) return null; var invocationList = o.GetInvocationList(); if (invocationList != null) { // DataContext changes are tracked through StandardChangeTracker object changeTracker = (from i in invocationList where i.Target.GetType().FullName == "System.Data.Linq.ChangeTracker+StandardChangeTracker" select i.Target).FirstOrDefault(); if (changeTracker != null) { object services = GetFieldValue(changeTracker, "services"); return (DataContext)GetFieldValue(services, "context"); } } return null; } private static object GetFieldValue(object instance, string propertyName) { return instance.GetType().GetField(propertyName, BindingFlags.Instance | BindingFlags.NonPublic).GetValue(instance); }
source share