Partager via


How to: Manually Open the Connection from the Object Context (Entity Framework)

This topic provides an example of how to manually open a connection from the object context. For more information, see Managing the Object Context (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).

Example

This example manually opens the connection, then executes a query and saves the changes. The connection is closed when the context goes out of scope and is disposed.

' Define the order ID for the order we want.
Dim orderId = 43661

Using advWorksContext As New AdventureWorksEntities()
    Try
        ' Explicitly open the connection.
        advWorksContext.Connection.Open()

        ' Execute a query to return an order.
        Dim order As SalesOrderHeader = _
            advWorksContext.SalesOrderHeader.Where( _
            "it.SalesOrderID = @orderId", New ObjectParameter("orderId", orderId)) _
            .Execute(MergeOption.AppendOnly).First()

        ' Change the status of the order.
        order.Status = 1

        ' Save changes.
        If 0 < advWorksContext.SaveChanges() Then
            Console.WriteLine("Changes saved.")
        End If
    Catch ex As InvalidOperationException
        Console.WriteLine(ex.ToString())
    End Try
    ' The connection is closed when the object context
    ' is disposed because it is no longer in scope.
End Using
// Define the order ID for the order we want.
int orderId = 43661;

using (AdventureWorksEntities advWorksContext =
    new AdventureWorksEntities())
{
    try
    {
        // Explicitly open the connection.    
        advWorksContext.Connection.Open();

        // Execute a query to return an order.
        SalesOrderHeader order =
            advWorksContext.SalesOrderHeader.Where(
            "it.SalesOrderID = @orderId", new ObjectParameter("orderId", orderId))
            .Execute(MergeOption.AppendOnly).First();


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

        // Save changes.
        if (0 < advWorksContext.SaveChanges())
        {
            Console.WriteLine("Changes saved.");
        }
    }
    catch (InvalidOperationException ex)
    {
        Console.WriteLine(ex.ToString());
    }

    // The connection is closed when the object context
    // is disposed because it is no longer in scope.
}

See Also

Tasks

How to: Manage the Connection in a Long-Running Object Context (Entity Framework)
How to: Use EntityConnection with an Object Context (Entity Framework)