I'm creating extensions for my EntityFramework objects as described in How to: Customize Generated Data Objects but in some of those extensions I need to get the instance's ObjectContext to look up some other values in the model. I've found Tip 24 – How to get the ObjectContext from an Entity but that was written a couple years ago, which is referenced in this similar SO question but I'm really hoping there's a better answer now.
Surely this must be something that's needed frequently enough that retrieval of an Entity's object context from the entity itself should be supported with an official method.
Thanks in advance for any more recent information on this implementation.
No there is not any such method. The described workaround looks like the only option because the entity is derived from
EntityObject
which is defined as:As I know only
IEntityWithRelationships.RelationshipManager
leads toObjectContext
. This wasn't changed in EF 4.Also it is not really common to access the context from the entity. I can imagine that this can be helpful in case of implementing Active Record Pattern on top of EF but in such case you would also have probably control over creating the context inside the static method of the entity so you should be able to set it to the entity. In other cases I would say that it is something you should avoid as much as possible.