locked
How do we get EntityKey in ObjectMaterialized event RRS feed

  • Question

  • In the previous version of OData, I used to hook ObjectMaterialized and SavingChanges events from ObjectContext in order to trace database access.

    protected void ObjectContext_ObjectMaterialized(object sender, ObjectMaterializedEventArgs e)
    {
        EntityObject entity = e.Entity as EntityObject;
        EntityKey key = entity.EntityKey;
        string keys = "";
        foreach (EntityKeyMember keyval in key.EntityKeyValues)
        {
            keys += keyval.Value.ToString() + " ";
        }
        Debug.WriteLine(String.Format("User {0} GET {1}: {2}", user, entity.GetType().Name, keys));
    }

    When Entities were derived from EntityObject, this was easy.

    Now with VS 2012 RTM, this has changed. The ObjectContext has been replaced by a DBContext containing an ObjectContext. Hooking to the same events works but Entities are stand alone classes now, they are no longer derived from EntityObject.

    What we receive now in the event is a System.Data.Entity.Dynamicproxies.myclass.

    I see an EntityKey buried somewhere in this class in the debugger, however I cannot programatically dig into this architecture because I have now idea how to cast this stuff.

    So how do I get to the EntityKey property without using reflexion?

    Thanks


    • Edited by plebel Monday, October 22, 2012 12:52 PM
    Monday, October 22, 2012 12:51 PM

Answers

  • Hi,

    To get an EntityKey object you will need to drop down to the ObjectContext, something like this:

    ((IObjectContextAdapter)myContext).ObjectContext.ObjectStateManager.GetObjectStateEntry(myEntity).EntityKey

    ~Rowan 

    We are seeing a lot of great Entity Framework questions (and answers) from the community on Stack Overflow. As a result, our team is going to spend more time reading and answering questions posted on Stack Overflow. We would encourage you to post questions on Stack Overflow using the entity-framework tag. We will also continue to monitor the Entity Framework forum.

    • Proposed as answer by Rowan Miller Monday, October 22, 2012 6:04 PM
    • Marked as answer by Alexander Sun Monday, November 5, 2012 9:31 AM
    Monday, October 22, 2012 6:04 PM