다음을 통해 공유


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

이 항목에서는 장기 실행 개체 컨텍스트에 대한 연결을 수동으로 여는 방법에 대한 예제를 제공합니다. 또한 컨텍스트에 대해 Dispose를 호출하여 연결이 해제되는지 확인하는 방법을 보여 줍니다.

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

참고 항목

작업

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

개념

연결 및 트랜잭션 관리(Entity Framework)