none
How to get from an instance of a EntityObject back to the ObjectContext

    Question

  • 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.

     

    Code Snippet

    static void Main(string[] args)

    {

    Entities e = new Entities();

    Model.MenuKey key = (from m in e.MenuKeys

    select m).First();

    Model.Coupon coup = key.Foo();

    }

     

     

    And in some file elsewhere:

     

    Code Snippet

    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?

     

    Thanks!  -pb

    Wednesday, August 27, 2008 8:49 PM

Answers

  • 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:

     

    Code Snippet

    ((ObjectQuery)((IEntityWithRelationships)this).RelationshipManager.GetAllRelatedEnds().First().CreateSourceQuery()).Context

     

     

    but this method is not very fast and in general not recommended because of its constraints.

     

    5. As a last resort, you can use reflection to get the context from some internal data structures, such as RelationshipManager, but that is completely unsupported.

     

     

    Wednesday, August 27, 2008 10:55 PM