Export (0) Print
Expand All

How to: Use EntityConnection with an Object Context (Entity Framework)

This topic provides an example of how to supply an existing EntityConnection for the object context to use. For more information, see Connection Strings (Entity Framework).

The example in this topic is based on the AdventureWorks Sales Model (EDM). To run the code in this example, you must have already added the AdventureWorks Sales Model to your project and configured your project to use the Entity Framework. To do this, complete the procedure in How to: Use the Entity Data Model Wizard (Entity Framework).


This example creates an EntityConnection that is passed into the constructor of a long-running ObjectContext. The connection is opened manually. Both the EntityConnection ObjectContext are disposed manually.

// Define the order ID for the order we want.
int orderId = 43661;

// Create an EntityConnection.
EntityConnection conn =
    new EntityConnection("name=AdventureWorksEntities");

// Create a long-running context with the connection.
AdventureWorksEntities advWorksContext =
    new AdventureWorksEntities(conn);

    // Explicitly open the connection.
    if (conn.State != ConnectionState.Open)

    // Execute a query to return an order.
    SalesOrderHeader order =
        "it.SalesOrderID = @orderId", new ObjectParameter("orderId", orderId))

    // Change the status of the order.
    order.Status = 1;

    // Save changes.
    if (0 < advWorksContext.SaveChanges())
        Console.WriteLine("Changes saved.");

    // Load the order's items.

    // Delete the first item.

    // Save changes again.
    if (0 < advWorksContext.SaveChanges())
        Console.WriteLine("Changes saved.");
catch (InvalidOperationException ex)
    // Explicitly dispose of the context and the connection. 

See Also

Community Additions

© 2014 Microsoft