Freigeben über


Gewusst wie: Erstellen eines EntityKey (Entity Framework)

Die EntityKey-Klasse stellt den Schlüssel eines Entitätsobjekts dar. Sie können eine Instanz von EntityKey mit den Klassenkonstruktoren erstellen, oder Sie können die statische CreateEntityKey-Methode von ObjectContext verwenden, um einen EntityKey für ein bestimmtes Objekt zu generieren. Der Entitätsschlüssel wird verwendet, um ein Objekt in die Datenquelle einzufügen oder ein bestimmtes Objekt aus der Datenquelle zurückzugeben. Weitere Informationen finden Sie unter Arbeiten mit Entitätsschlüsseln (Entity Framework).

Die Beispiele in diesem Thema beruhen auf dem AdventureWorks Sales-Modell. Zum Ausführen des Codes in diesem Beispiel muss dem Projekt bereits das AdventureWorks Sales-Modell hinzugefügt und das Projekt für die Verwendung von Entity Framework konfiguriert worden sein. Führen Sie dazu die Verfahren unter Gewusst wie: Manuelles Konfigurieren eines Entity Framework-Projekts und Gewusst wie: Manuelles Definieren der Modell- und Zuordnungsdateien (Entity Framework) durch.

Beispiel

Im folgenden Beispiel wird eine Instanz von EntityKey mithilfe eines angegebenen Schlüssel-Wert-Paars und des qualifizierten Namens der Entitätenmenge erstellt. Dieser Schlüssel wird dann verwendet, um das Objekt selbst abzurufen.

Using context As New AdventureWorksEntities()
    Dim entity As Object = Nothing
    Dim entityKeyValues As IEnumerable(Of KeyValuePair(Of String, Object)) = _
        New KeyValuePair(Of String, Object)() {New KeyValuePair(Of String, Object)("SalesOrderID", 43680)}

    ' Create the key for a specific SalesOrderHeader object. 
    Dim key As New EntityKey("AdventureWorksEntities.SalesOrderHeaders", entityKeyValues)

    ' Get the object from the context or the persisted store by its key. 
    If context.TryGetObjectByKey(key, entity) Then
        Console.WriteLine("The requested " & entity.GetType().FullName & " object was found")
    Else
        Console.WriteLine("An object with this key could not be found.")
    End If
End Using
using (AdventureWorksEntities context =
    new AdventureWorksEntities())
{
    Object entity = null;
    IEnumerable<KeyValuePair<string, object>> entityKeyValues =
        new KeyValuePair<string, object>[] {
            new KeyValuePair<string, object>("SalesOrderID", 43680) };

    // Create the  key for a specific SalesOrderHeader object. 
    EntityKey key = new EntityKey("AdventureWorksEntities.SalesOrderHeaders", entityKeyValues);

    // Get the object from the context or the persisted store by its key.
    if (context.TryGetObjectByKey(key, out entity))
    {
        Console.WriteLine("The requested " + entity.GetType().FullName +
            " object was found");
    }
    else
    {
        Console.WriteLine("An object with this key " +
            "could not be found.");
    }
}

Verwenden Sie für eine unabhängige Zuordnung die im folgenden Beispiel beschriebene Methode, um eine Beziehung zu definieren. Definieren Sie für eine Fremdschlüsselzuordnung Beziehungen, indem Sie den Wert der Fremdschlüsseleigenschaften des abhängigen Objekts festlegen. Weitere Informationen finden Sie unter Definieren und Verwalten von Beziehungen (Entity Framework).

Im folgenden Beispiel wird eine Instanz von EntityKey mithilfe eines angegebenen Schlüsselnamens, eines Schlüsselwerts und des qualifizierten Namens der Entitätenmenge erstellt. Dieser Schlüssel wird dann verwendet, um ein Objekt anzufügen und eine Beziehung zu definieren.

Using context As New AdventureWorksEntities()
    Try
        ' Create the key that represents the order. 
        Dim orderKey As New EntityKey("AdventureWorksEntities.SalesOrderHeaders", "SalesOrderID", orderId)

        ' Create the stand-in SalesOrderHeader object 
        ' based on the specified SalesOrderID. 
        Dim order As New SalesOrderHeader()
        order.EntityKey = orderKey

        ' Assign the ID to the SalesOrderID property to matche the key. 
        order.SalesOrderID = CInt(orderKey.EntityKeyValues(0).Value)

        ' Attach the stand-in SalesOrderHeader object. 
        context.SalesOrderHeaders.Attach(order)

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

        context.SaveChanges()
    Catch generatedExceptionName As InvalidOperationException
        Console.WriteLine("Ensure that the key value matches the value of the object's ID property.")
    Catch generatedExceptionName As UpdateException
        Console.WriteLine("An error has occured. Ensure that an object with the '{0}' key value exists.", orderId)
    End Try
End Using
using (AdventureWorksEntities context =
    new AdventureWorksEntities())
{
    try
    {
        // Create the key that represents the order.
        EntityKey orderKey =
            new EntityKey("AdventureWorksEntities.SalesOrderHeaders",
                "SalesOrderID", orderId);

        // Create the stand-in SalesOrderHeader object
        // based on the specified SalesOrderID.
        SalesOrderHeader order = new SalesOrderHeader();
        order.EntityKey = orderKey;

        // Assign the ID to the SalesOrderID property to matche the key.
        order.SalesOrderID = (int)orderKey.EntityKeyValues[0].Value;

        // Attach the stand-in SalesOrderHeader object.
        context.SalesOrderHeaders.Attach(order);

        // 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 = orderId,
            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);

        context.SaveChanges();
    }
    catch (InvalidOperationException)
    {
        Console.WriteLine("Ensure that the key value matches the value of the object's ID property.");
    }
    catch (UpdateException)
    {
        Console.WriteLine("An error has occured. Ensure that an object with the '{0}' key value exists.",
        orderId);
    }
}

Im folgenden Beispiel wird mithilfe von Schlüsselwerten eines getrennten Objekts eine Instanz von EntityKey erstellt. Dieser Schlüssel wird dann verwendet, um eine angefügte Instanz des Objekts abzurufen.

Private Shared Sub ApplyItemUpdates(ByVal updatedItem As SalesOrderDetail)
    ' Define an ObjectStateEntry and EntityKey for the current object. 
    Dim key As EntityKey
    Dim originalItem As Object

    Using context As New AdventureWorksEntities()
        ' Create the detached object's entity key. 
        key = context.CreateEntityKey("SalesOrderDetails", updatedItem)

        ' Get the original item based on the entity key from the context 
        ' or from the database. 
        If context.TryGetObjectByKey(key, originalItem) Then
            ' Call the ApplyCurrentValues method to apply changes 
            ' from the updated item to the original version. 
            context.ApplyCurrentValues(key.EntitySetName, updatedItem)
        End If

        context.SaveChanges()
    End Using
End Sub
private static void ApplyItemUpdates(SalesOrderDetail updatedItem)
{
    // Define an ObjectStateEntry and EntityKey for the current object. 
    EntityKey key = default(EntityKey);
    object originalItem = null;

    using (AdventureWorksEntities context = new AdventureWorksEntities())
    {
        // Create the detached object's entity key. 
        key = context.CreateEntityKey("SalesOrderDetails", updatedItem);

        // Get the original item based on the entity key from the context 
        // or from the database. 
        if (context.TryGetObjectByKey(key, out originalItem))
        {
            // Call the ApplyCurrentValues method to apply changes 
            // from the updated item to the original version. 
            context.ApplyCurrentValues(key.EntitySetName, updatedItem);
        }

        context.SaveChanges();
    }
}

Siehe auch

Aufgaben

Gewusst wie: Zurückgeben eines bestimmten Objekts anhand seines Schlüssels (Entity Framework)

Konzepte

Arbeiten mit Objekten (Entity Framework)