Export (0) Print
Expand All

How to: Identify that a POCO Entity is a Proxy

.NET Framework 4

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 static bool IsProxy(object type)
    return type != null && ObjectContext.GetObjectType(type.GetType()) != type.GetType();

public static void TestIfEntityIsProxy()
    using (POCOAdventureWorksEntities context = new POCOAdventureWorksEntities())
        LineItem newItem = context.CreateObject<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.2942M;
        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.
        bool isLazyLoading = IsProxy(newItem);

        // Determine if it is a change tracking proxy by
        // making a change and verifying that it was detected.
        newItem.OrderQty = 2;
        bool isChangeTracking = context.ObjectStateManager
                                  .State == EntityState.Modified;

See Also

Community Additions

© 2014 Microsoft