Hi; is this the right forum for questions on the RTM version of the Entity Framework?
I have what's probably an unusual question that I'd really like to have answered, if possible. I'm writing code for a method inside an instance of a class derived from EntityObject (i.e. it's an instance of a row in my database), and I'm trying to execute a query against a seemingly unrelated table in the schema. Because of performance and memory usage concerns, I'd like not to instantiate another instance of the ObjectContext-derived-class, but rather navigate to it in code and use the already-instantiated ObjectContext. Is this possible, and if so, how?
For clarity, here's an example in code.
static void Main(string args)
Entities e = new Entities();
Model.MenuKey key = (from m in e.MenuKeys
Model.Coupon coup = key.Foo();
And in some file elsewhere:
public partial class MenuKey
public Coupon Foo()
// Get the object context (Model.Entities)
// return (from c in entities
// where -blah-
// select c).First();
So the question is "how do I get the ObjectContext as shown in the first commented line of the 2nd snippet?" Or is there some better way I'm not seeing to do what's needed?
It is not directly possible to get from entity object to the context. In some situations you may be able to get to the context using some tricks (see below) and/or reflection, but that is not recommended as it increases coupling between entities and the infrastructure for persistence.
The alternatives you may want to consider:
1. Move the method to a service class (CouponRetrievalService, etc) (why is it declared on the entity type itself if it performs operations on completely unrelated objects?) and pass ObjectContext in the constructor of the service. This is the recommended approach.
2. Pass the context as a parameter to the Foo() method.
3. Have some form of an ambient context (global or thread-local static variable)
4. If your entity has at least one relationship, you can get to the context using the following trick: