Export (0) Print
Expand All

ObjectContext.Connection Property

Gets the connection used by the object context.

Namespace:  System.Data.Objects
Assembly:  System.Data.Entity (in System.Data.Entity.dll)

public DbConnection Connection { get; }

Property Value

Type: System.Data.Common.DbConnection
A DbConnection object that is the connection.

This property returns the connection object that was passed into the constructor or created during construction. The connection’s ownership is determined by the constructors used.

This example creates an EntityConnection object that is passed into the constructor of a long-running ObjectContext. The connection is opened manually. Both the EntityConnection object and the ObjectContext object are disposed of 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. 

Windows 7, Windows Vista, Windows XP SP2, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003

The .NET Framework and .NET Compact Framework do not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

.NET Framework

Supported in: 3.5 SP1

Community Additions

© 2014 Microsoft