共用方式為


HOW TO:在長時間執行的物件內容中管理連接 (Entity Framework)

本主題提供的範例將示範如何針對長時間執行的物件內容手動開啟連接。 此範例也會示範如何在此內容上呼叫 Dispose,以確保連接已釋放。

本主題的範例是根據 AdventureWorks 銷售模型。 若要執行此範例中的程式碼,您必須已經將 AdventureWorks Sales Model 加入到專案中,並設定您的專案使用 Entity Framework。 若要這樣做,請完成 HOW TO:使用實體資料模型精靈 (Entity Framework) 中的程序。

範例

此範例會手動開啟長時間執行之 ObjectContext 所使用的連接,然後執行查詢及儲存變更。 當處置 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();
}

另請參閱

工作

HOW TO:從物件內容手動開啟連接 (Entity Framework)

概念

管理連接和交易 (Entity Framework)