EDIT: I'd like to get a definitive answer on whether or not it's possible to determine which ObjectContext is tracking which Entities. Is there a particular property that says "Entity x belongs to this context?"
If you have references to all possible ObjectContext
instances, you can determine to which one a given entity instance is attached to by calling their .ObjectStateManager.TryGetObjectStateEntry(Object, out ObjectStateEntry) methods - the right one will return true. If you don't, there is no straightforward public API to get from an entity instance to an ObjectContext instance. If the entity has relationships and implements IEntityWithRelationships, you can retrieve its RelationshipManager, ask it to get any related end (aka "navigation property") with GetAllRelatedEnds, ask the related end to create a query with CreateSourceQuery, cast it to an ObjectQuery and finally retrieve the .Context. You don't have to do all this if you're willing to use reflection to access internal members of Entity Framework classes, but still the best you can get from an instance of an entity without relationships is an ObjectStateManager
, not ObjectContext
. Better yet, if you require to access the ObjectContext
from an entity instance, you can use a custom entity base class (with custom code generation template or otherwise) with an ObjectContext
property which you can populate and clear in the event handler for ObjectStateManagerChanged.