EF POCOs and GetObjectStateEntry

Even when working with POCOs, the EF’s ObjectContext can track the objects using ObjectStateEntry objects just as it does for entities that inherit from EntityObject.

I was thinking about ObjectContext.ObjectStateManager.GetObjectStateEntry. This method has two overloads. One takes an entity and the other takes an EntityKey of an entity. Then it returns the ObjectStateEntry being maintained to track that particular entity.

In more detail, the signature for the first overload is

GetObjectStateEntry(object entity)

So it doesn’t necessarily require an EntityObject.

I ran a query using a context which returned a POCO class.

The POCO class was one designed for snapshot detection. There are no virtual properties and therefore no proxy EntityObject is created on behalf of this object.

I requested the entry:

var ose= context.ObjectStateManager.GetObjectStateEntry(contact);

And voila, even though it was a simple object, the context was still able to find the ObjectStateEntry and return it.

There are a lot of What-Ifs around using POCOs. There will are definitely be some scenarios where you won’t get the behavior you might expect from an EntityObject. Sometimes using proxies will fix that, such as in the case of lazy loading. But it will take time to work through the various possibilities.

  Sign up for my newsletter so you don't miss my conference & Pluralsight course announcements!  

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.