Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
Export (0) Print
Expand All

How to: Create a POCO Entity with Proxies

.NET Framework 4

The example in this topic shows how to create POCO entities with proxies. To create POCO entities with proxies, the POCO class must meet the requirements described in Requirements for Creating POCO Proxies.

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.


This example creates a new LineItem object by using the CreateObject method, and then adds the new LineItem to an existing Order.

// Specify the order to update.
int orderId = 43680;

using (POCOAdventureWorksEntities context =
        new POCOAdventureWorksEntities())
        // Enable lazy loading.
        context.ContextOptions.LazyLoadingEnabled = true;

        Order order = context.Orders.
                          Where(o => o.SalesOrderID == orderId).First();
        // Create a new item and add it to the order.
        // The Entity Framework is going to generate 
        // proxy object for the newItem object. 
        LineItem newItem = context.CreateObject<LineItem>();
        newItem.SalesOrderDetailID = 0;
        // Assign the order to the new LineItem. 
        newItem.SalesOrderID = orderId;
        newItem.OrderQty = 1;
        newItem.ProductID = 750;
        newItem.UnitPriceDiscount = 0;
        newItem.UnitPrice = 2171.2942M;
        newItem.ModifiedDate = DateTime.Today;
        newItem.rowguid = Guid.NewGuid();
        newItem.SpecialOfferID = 1;

        // Add the new item to the order.
        // The order will be added to the context because 
        // we are working with POCO proxies.

        // The state of the newItem is Added.

        // Change the status and ship date of an existing order.
        order.ShipDate = DateTime.Today;

        // The sate of the order item is Modified.

        // The newItem is set to Unchanged.

        // Change the newly added item.
        newItem.OrderQty = 2;

        // The changes are tracked as they occur and the state of the object is Modified.

        // Delete the newly created object.

        // Save changes in the object context to the database 
        // after first detecting changes again.
    catch (UpdateException ex)
    catch (InvalidOperationException ex)

See Also

Community Additions

© 2015 Microsoft