Share via


Procedura: gestire la connessione in un contesto dell'oggetto con esecuzione prolungata (Entity Framework)

In questo argomento viene fornito un esempio di apertura manuale di una connessione per il contesto di un oggetto con esecuzione prolungata. Nell'esempio viene inoltre illustrato come fare in modo che la connessione venga rilasciata chiamando Dispose nel contesto.

L'esempio incluso in questo argomento è basato sul modello descritto in Modello Sales di AdventureWorks. Per eseguire il codice incluso in questo esempio, è necessario avere già aggiunto il modello Sales di AdventureWorks al progetto e avere configurato il progetto per l'utilizzo di Entity Framework. A tale scopo, completare la procedura descritta in Procedura: utilizzare la procedura guidata Entity Data Model (Entity Framework).

Esempio

In questo esempio viene aperta manualmente la connessione utilizzata da un oggetto ObjectContext con esecuzione prolungata, quindi viene eseguita una query e vengono salvate le modifiche. La connessione viene chiusa quando viene eliminato ObjectContext.

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

' Create a long-running context. 
Dim context As New AdventureWorksEntities()
Try
    If context.Connection.State <> ConnectionState.Open Then
        ' Explicitly open the connection. 
        context.Connection.Open()
    End If

    ' 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 an existing order. 
    order.Status = 1

    ' You do not have to call the Load method to load the details for the order, 
    ' because lazy loading is set to true 
    ' by the constructor of the AdventureWorksEntities object. 
    ' With lazy loading set to true the related objects are loaded when 
    ' you access the navigation property. In this case SalesOrderDetails. 

    ' Delete the first item in the order. 
    context.DeleteObject(order.SalesOrderDetails.First())

    ' Save changes. 
    If 0 < context.SaveChanges() Then
        Console.WriteLine("Changes saved.")
    End If

    ' Create a new SalesOrderDetail object. 
    ' You can use the static CreateObjectName method (the Entity Framework 
    ' adds this method to the generated entity types) instead of the new operator: 
    ' SalesOrderDetail.CreateSalesOrderDetail(1, 0, 2, 750, 1, (decimal)2171.2942, 0, 0, 
    ' Guid.NewGuid(), DateTime.Today)); 
    Dim detail = New SalesOrderDetail With
    {
        .SalesOrderID = 0,
        .SalesOrderDetailID = 0,
        .OrderQty = 2,
        .ProductID = 750,
        .SpecialOfferID = 1,
        .UnitPrice = CDec(2171.2942),
        .UnitPriceDiscount = 0,
        .LineTotal = 0,
        .rowguid = Guid.NewGuid(),
        .ModifiedDate = DateTime.Now
    }

    order.SalesOrderDetails.Add(detail)


    ' Save changes again. 
    If 0 < context.SaveChanges() Then
        Console.WriteLine("Changes saved.")
    End If
Catch ex As InvalidOperationException
    Console.WriteLine(ex.ToString())
Finally
    ' Explicitly dispose of the context, 
    ' which closes the connection. 
    context.Dispose()
// Define the order ID for the order we want.
int orderId = 43680;

// Create a long-running context.
AdventureWorksEntities context =
    new AdventureWorksEntities();

try
{
    if (context.Connection.State != ConnectionState.Open)
    {
        // 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 an existing order.
    order.Status = 1;

    // You do not have to call the Load method to load the details for the order,
    // because  lazy loading is set to true 
    // by the constructor of the AdventureWorksEntities object. 
    // With  lazy loading set to true the related objects are loaded when
    // you access the navigation property. In this case SalesOrderDetails.

    // Delete the first item in the order.
    context.DeleteObject(order.SalesOrderDetails.First());

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

    // Create a new SalesOrderDetail object.
    // You can use the static CreateObjectName method (the Entity Framework
    // adds this method to the generated entity types) instead of the new operator:
    // SalesOrderDetail.CreateSalesOrderDetail(1, 0, 2, 750, 1, (decimal)2171.2942, 0, 0,
    //                                         Guid.NewGuid(), DateTime.Today));
    SalesOrderDetail detail = new SalesOrderDetail
    {
        SalesOrderID = 0,
        SalesOrderDetailID = 0,
        OrderQty = 2,
        ProductID = 750,
        SpecialOfferID = 1,
        UnitPrice = (decimal)2171.2942,
        UnitPriceDiscount = 0,
        LineTotal = 0,
        rowguid = Guid.NewGuid(),
        ModifiedDate = DateTime.Now
    };

    order.SalesOrderDetails.Add(detail);


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

Vedere anche

Attività

Procedura: aprire manualmente la connessione dal contesto dell'oggetto (Entity Framework)

Concetti

Gestione di connessioni e transazioni (Entity Framework)