How to: Identify that a POCO Entity is a Proxy

How to: Identify that a POCO Entity is a Proxy

Visual Studio 2010

This topic shows how to identify whether a POCO entity is a proxy. There are occasions when you would like to test whether your POCO object is actually a proxy. When you create a POCO entity by using the CreateObject method, if the POCO type does not meet the requirements described in Requirements for Creating POCO Proxies, a POCO entity will be created instead of a proxy object. For more information, see Working with POCO Entities.

The example in this topic uses the POCO classes that are defined in How to: Define POCO Entities and an AdventureWorks-based data model that is defined in How to: Customize Modeling and Mapping Files to Work with Custom Objects.


The following example uses the CreateObject method to create a proxy object. The example then verifies whether the object is a proxy object by comparing the POCO type to the generated proxy type. If the types are not the same, then it is a proxy. If it is a proxy object, it is at a minimum a lazy-loading proxy object. To determine if it is also a change-tracking proxy object, we can see if changes are being tracked.

Public Shared Function IsProxy(ByVal type As Object) As Boolean
    Return type IsNot Nothing AndAlso ObjectContext.GetObjectType(type.GetType()) <> type.GetType()
End Function

Public Shared Sub TestIfEntityIsProxy()
    Using context As New POCOAdventureWorksEntities()
        Dim newItem As LineItem = context.CreateObject(Of LineItem)()
        newItem.SalesOrderDetailID = 0
        ' Assign the order to the new LineItem. 
        newItem.SalesOrderID = 43680
        newItem.OrderQty = 1
        newItem.ProductID = 750
        newItem.UnitPriceDiscount = 0
        newItem.UnitPrice = 2171.2942D
        newItem.ModifiedDate = DateTime.Today
        newItem.rowguid = Guid.NewGuid()
        newItem.SpecialOfferID = 1


        ' Determine if the instance is a proxy. 
        ' If it is a proxy it supports lazy loading. 
        Dim isLazyLoading As Boolean = IsProxy(newItem)

        ' Determine if it is a change tracking proxy by 
        ' making a change and verifying that it was detected. 
        newItem.OrderQty = 2
        Dim isChangeTracking As Boolean = _
            context.ObjectStateManager.GetObjectStateEntry(newItem).State = EntityState.Modified
    End Using
End Sub

See Also

Community Additions

© 2016 Microsoft