Gewusst wie: Verwenden von EntityConnection mit einem Objektkontext (Entity Framework)

In diesem Thema wird anhand eines Beispiels gezeigt, wie dem Objektkontext eine bestehende EntityConnection zur Verfügung gestellt werden kann. Weitere Informationen finden Sie unter Verbindungszeichenfolgen (Entity Framework).

Das Beispiel in diesem Thema beruht auf dem AdventureWorks Sales-Modell. Um den Code in diesem Beispiel auszuführen, müssen Sie Ihrem Projekt bereits das "AdventureWorks Sales"-Modell hinzugefügt und das Projekt für die Verwendung von Entity Framework konfiguriert haben. Führen Sie dazu das Verfahren unter Gewusst wie: Verwenden des Entity Data Model-Assistenten (Entity Framework) aus.

Beispiel

In diesem Beispiel wird eine EntityConnection erstellt, die dem Konstruktor eines ObjectContext mit langer Laufzeit übergeben wird. Die Verbindung wird manuell geöffnet. Sowohl EntityConnection als auch ObjectContext werden manuell freigegeben.

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

' Create an EntityConnection. 
Dim conn As New EntityConnection("name=AdventureWorksEntities")

' Create a long-running context with the connection. 
Dim context As New AdventureWorksEntities(conn)

Try
    ' Explicitly open the connection. 
    If conn.State <> ConnectionState.Open Then
        conn.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 the 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 and the connection. 
    context.Dispose()
    conn.Dispose()
// Define the order ID for the order we want.
int orderId = 43680;

// Create an EntityConnection.
EntityConnection conn =
    new EntityConnection("name=AdventureWorksEntities");

// Create a long-running context with the connection.
AdventureWorksEntities context =
    new AdventureWorksEntities(conn);

try
{
    // Explicitly open the connection.
    if (conn.State != ConnectionState.Open)
    {
        conn.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;

    // 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 = 1,
        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 and the connection. 
    context.Dispose();
    conn.Dispose();
}

Siehe auch

Aufgaben

Gewusst wie: Verwalten der Verbindung in einem Objektkontext mit langer Laufzeit (Entity Framework)
Gewusst wie: Manuelles Öffnen der Verbindung aus dem Objektkontext (Entity Framework)