Sdílet prostřednictvím


How to: Manually Open the Connection from the Object Context

This topic provides an example of how to manually open a connection from the object context.

The example in this topic is based on the AdventureWorks Sales Model. 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.

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 As Integer = 43680

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

    ' Execute a query to return an order. 
    Dim order As SalesOrderHeader = context.SalesOrderHeaders.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 < context.SaveChanges() Then
        Console.WriteLine("Changes saved.")
    End If
    ' 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 = 43680;

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

    // Execute a query to return an order.
    SalesOrderHeader order =
        context.SalesOrderHeaders.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 < context.SaveChanges())
    {
        Console.WriteLine("Changes saved.");
    }
    // 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
How to: Use EntityConnection with an Object Context