다음을 통해 공유


방법: 수동으로 개체 컨텍스트의 연결 열기(Entity Framework)

이 항목에서는 개체 컨텍스트의 연결을 수동으로 여는 방법에 대한 예제를 제공합니다.

이 항목의 예제는 AdventureWorks Sales 모델을 기반으로 합니다. 이 예제의 코드를 실행하려면 프로젝트에 AdventureWorks Sales 모델을 추가하고 Entity Framework를 사용하도록 프로젝트를 구성해야 합니다. 이렇게 하려면 방법: 엔터티 데이터 모델 마법사 사용(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.
}

참고 항목

작업

방법: 장기 실행 개체 컨텍스트의 연결 관리(Entity Framework)
방법: 개체 컨텍스트에서 EntityConnection 사용(Entity Framework)