Gewusst wie: Hinzufügen, Ändern und Löschen von Objekten (Entity Framework)

In diesem Thema wird anhand eines Beispiels gezeigt, wie Objekte in einem Objektkontext geändert und die Daten in einer Datenbank gespeichert werden.

Das Beispiel in diesem Thema beruht auf dem Adventure Works Sales-Modell. Zum Ausführen des Codes in diesem Thema muss dem Projekt bereits das Adventure Works Sales-Modell hinzugefügt und das Projekt zur Verwendung von Entity Framework konfiguriert worden sein. Weitere Informationen finden Sie unter Gewusst wie: Verwenden des Assistenten für Entity Data Model (Entity Framework) bzw. Gewusst wie: Manuelles Konfigurieren eines Entity Framework-Projekts und Gewusst wie: Manuelles Definieren eines Entity Data Model (Entity Framework).

Beispiel

In diesem Beispiel gibt eine Objektabfrage auf Grundlage einer angegebenen SalesOrderID ein einzelnes SalesOrderHeader-Objekt zurück. Der Status dieser Bestellung wird von 5 (geliefert) in 1 (in Bearbeitung) geändert, ein neues Element wird der Bestellung hinzugefügt, und das erste bestehende Element wird gelöscht. Die SaveChanges-Methode wird aufgerufen, um die Änderungen in der Datenbank zu speichern. Der resultierende Status der Bestellung wird anschließend in der Konsole angezeigt.

' Specify the order to update. 
Dim orderId As Integer = 43680

Using context As New AdventureWorksEntities()
    Try
        Dim order = (From o In context.SalesOrderHeaders
            Where o.SalesOrderID = orderId
            Select o).First()

        ' Change the status and ship date of an existing order. 
        order.Status = 1
        order.ShipDate = DateTime.Today

        ' 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())

        ' 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 in the object context to the database. 
        Dim changes As Integer = context.SaveChanges()

        Console.WriteLine(changes.ToString() + " changes saved!")
        Console.WriteLine("Updated item for order: {0}", order.SalesOrderID.ToString())

        For Each item As SalesOrderDetail In order.SalesOrderDetails
            Console.WriteLine("Item ID: {0}", item.SalesOrderDetailID.ToString())
            Console.WriteLine("Product: {0}", item.ProductID.ToString())
            Console.WriteLine("Quantity: {0}", item.OrderQty.ToString())
        Next
    Catch ex As UpdateException
        Console.WriteLine(ex.ToString())
    End Try
End Using
// Specify the order to update.
int orderId = 43680;

using (AdventureWorksEntities context =
    new AdventureWorksEntities())
{
    try
    {
        var order = (from o in context.SalesOrderHeaders
                     where o.SalesOrderID == orderId
                     select o).First();

        // Change the status and ship date of an existing order.
        order.Status = 1;
        order.ShipDate = DateTime.Today;

        // 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());

        // 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 in the object context to the database.
        int changes = context.SaveChanges();

        Console.WriteLine(changes.ToString() + " changes saved!");
        Console.WriteLine("Updated item for order: "
            + order.SalesOrderID.ToString());

        foreach (SalesOrderDetail item in order.SalesOrderDetails)
        {
            Console.WriteLine("Item ID: "
                + item.SalesOrderDetailID.ToString() + "  Product: "
                + item.ProductID.ToString() + "  Quantity: "
                + item.OrderQty.ToString());
        }
    }
    catch (UpdateException ex)
    {
        Console.WriteLine(ex.ToString());
    }
}

Siehe auch

Konzepte

Erstellen, Hinzufügen, Ändern und Löschen von Objekten (Entity Framework)
Arbeiten mit Objekten (Entity Framework)