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?”
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
If you have references to all possible
ObjectContextinstances, 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 anObjectStateManager, notObjectContext. Better yet, if you require to access theObjectContextfrom an entity instance, you can use a custom entity base class (with custom code generation template or otherwise) with anObjectContextproperty which you can populate and clear in the event handler for ObjectStateManagerChanged.