Cómo usar EntityConnection con un contexto del objeto (Entity Framework)

En este tema se proporciona un ejemplo de cómo suministrar una EntityConnection existente para que lo use el contexto del objeto. Para obtener más información, vea Administrar el contexto del objeto (Entity Framework).

El ejemplo de este tema se basa en el Modelo AdventureWorks Sales (EDM). Para ejecutar el código de este ejemplo, debe haber agregado ya el modelo de ventas de AdventureWorks al proyecto y haber configurado el proyecto para usar Entity Framework. Para ello, complete el procedimiento de Cómo usar el Asistente para Entity Data Model (Entity Framework).

Ejemplo

En este ejemplo se crea una EntityConnection que se pasa en el constructor de un ObjectContext de larga duración. La conexión se abre manualmente. Ambos, EntityConnection y ObjectContext se eliminan manualmente.

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

' Create an EntityConnection.
Dim conn As New EntityConnection("name=AdventureWorksEntities")

' Create a long-running context with the connection.
Dim advWorksContext As New AdventureWorksEntities(conn)

Try
    ' Explicitly open the connection.
    If Not conn.State = ConnectionState.Open Then
        conn.Open()
    End If

    ' 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

    ' Load the order's items.
    order.SalesOrderDetail.Load()

    ' Delete the first item.
    advWorksContext _
        .DeleteObject(order.SalesOrderDetail.First())

    ' Save changes again.
    If 0 < advWorksContext.SaveChanges() Then
        Console.WriteLine("Changes saved.")
    End If
Catch ex As InvalidOperationException
    Console.WriteLine(ex.ToString())
Finally
    ' Explicitly dispose of the context and the connection. 
    advWorksContext.Dispose()
    conn.Dispose()
End Try
// 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);

try
{
    // Explicitly open the connection.
    if (conn.State != ConnectionState.Open)
    {
        conn.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.");
    }

    // Load the order's items.
    order.SalesOrderDetail.Load();

    // Delete the first item.
    advWorksContext
        .DeleteObject(order.SalesOrderDetail.First());

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

Vea también

Tareas

Cómo administrar la conexión en un contexto del objeto de larga duración (Entity Framework)
Cómo abrir manualmente la conexión desde el contexto del objeto (Entity Framework)