共用方式為


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

本主題提供的範例將示範如何從物件內容手動開啟連接。

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

範例

此範例會手動開啟連接,然後執行查詢及儲存變更。 當內容超出範圍且遭到處置時,就會關閉連接。

' 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.
}

另請參閱

工作

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