How to instantiate POCO classes using ObjectContext.CreateObject <T> method

While working with POCO entities, proxies are created automatically in two situations. As we have seen already in the article How to perform Lazy Loading, by making a navigation property as virtual, the EF runtime creates proxies. And also, if we declare all the properties as virtual, entity framework creates change tracking proxies which handle change notification, lazy loading and relationship fix-up automatically.
But, we need to manually instantiate proxies for POCO entities while adding a POCO entity to the ObjectContext. By using CreateObject method of ObjectContext, we instantiate POCO classes.

We should note that even if we adopt Snapshot Change Tracking mechanism using DetectChanges method without using proxies, still we should use CreateObject method to instantiate POCO classes while adding or attaching POCO entities to the context.

To create proxy instances, we need to set the ContextOptions.ProxyCreationEnabled to true.

If you have not created POCO classes with Lazy loading and change tracking proxies functionality, the article - How to Create a POCO class in entity framework will help you.

The example code is given below. The below code performs the following.

  • Checks whether change tracking proxy works as soon as we modify a POCO entity by displaying ObjectStateEntry class properties - State and Entityset
  • Creates a proxy instance using CreateObject <T> method where T is the POCO type, in this case Customer POCO type and then add to the context.
  • After adding a POCO entity, display current values of newly added POCO entity using GetObjectStateEntries method.
code snippet to instantiate POCO classes

The output of the code is given below.

screen output of current values of a POCO entity