Udostępnij za pośrednictwem


How to: Create an EntityKey (Entity Framework)

The EntityKey class represents the key of an entity object. You can create an instance of EntityKey by using the class constructors, or you can use the static CreateEntityKey method of ObjectContext to generate an EntityKey for a specific object. The entity key is used to attach an object or to return a specific object from the data source. For more information, see Working with Entity Keys (Entity Framework).

The examples in this topic are based on the Adventure Works Sales Model. To run the code in this example, you must have already added the AdventureWorks Sales Model to your project and configured your project to use the Entity Framework. To do this, complete the procedures in How to: Manually Configure an Entity Framework Project and How to: Manually Define an Entity Data Model (Entity Framework).

Example

The following example creates an instance of EntityKey using a specified key/value pair and the qualified entity set name. This key is then used to retrieve the object itself.

Using advWorksContext As New AdventureWorksEntities
    Try
        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.SalesOrderHeader", entityKeyValues)

        ' Try to get the object from the context or the persisted store by its key.
        If advWorksContext.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
    Catch ex As EntitySqlException
        Console.WriteLine(ex.ToString)
    End Try
End Using
using (AdventureWorksEntities advWorksContext =
    new AdventureWorksEntities())
{
    try
    {
        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.SalesOrderHeader", entityKeyValues);

        // Get the object from the context or the persisted store by its key.
        if (advWorksContext.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.");
        }
    }
    catch (EntitySqlException ex)
    {
        Console.WriteLine(ex.ToString());
    }
}

The following example creates an instance of EntityKey using a specified key name, key value, and the qualified entity set name. This key is then used to attach an object and define a relationship.

' Specify the order to which to add the item.
Dim orderId = 43680

' Create the key that represents the order.
Dim orderKey As EntityKey = _
    New EntityKey("AdventureWorksEntities.SalesOrderHeader", _
        "SalesOrderID", orderId)

' Create an order that we can attach.
Dim order As New SalesOrderHeader()
order.EntityKey = orderKey

' Ensure that the ID property matches the key.
order.SalesOrderID = CType(orderKey.EntityKeyValues(0).Value, Integer)

Using context As AdventureWorksEntities = _
    New AdventureWorksEntities()
    Try
        ' Attach the newly created object.
        context.Attach(order)

        ' Create a new item using the static Create method 
        ' and add it to the attached order.
        order.SalesOrderDetail.Add( _
            SalesOrderDetail.CreateSalesOrderDetail(0, _
            0, 2, 750, 1, Convert.ToDecimal(2171.2942), 0, 0, _
            Guid.NewGuid(), DateTime.Today))

        context.SaveChanges()
    Catch ex As InvalidOperationException
        Console.WriteLine(String.Format("Ensure that the key value '{0}' " _
            & "matches the value of the '{1}' property.", _
            order.EntityKey.EntityKeyValues(0).Value, _
            order.EntityKey.EntityKeyValues(0).Key))
    Catch ex As UpdateException
        Console.WriteLine(String.Format("An error has occured. Ensure that " _
        & "an object with an value of '{0}' for key property '{1}' exists.", _
        order.EntityKey.EntityKeyValues(0).Value, _
        order.EntityKey.EntityKeyValues(0).Key))
    End Try
End Using
// Specify the order to which to add the item.
int orderId = 43680;

// Create the key that represents the order.
EntityKey orderKey =
    new EntityKey("AdventureWorksEntities.SalesOrderHeader",
        "SalesOrderID", orderId);

// Create an order that we can attach.
SalesOrderHeader order = new SalesOrderHeader();
order.EntityKey = orderKey;

// Ensure that the ID property matches the key.
order.SalesOrderID = (int)orderKey.EntityKeyValues[0].Value;

using (AdventureWorksEntities context =
    new AdventureWorksEntities())
{
    try
    {
        // Attach the newly created object.
        context.Attach(order);

        // Create a new item using the static Create method 
        // and add it to the attached order.
        order.SalesOrderDetail.Add(
            SalesOrderDetail.CreateSalesOrderDetail(0,
            0, 2, 750, 1, (decimal)2171.2942, 0, 0,
            Guid.NewGuid(), DateTime.Today));

        context.SaveChanges();
    }
    catch (InvalidOperationException)
    {
        Console.WriteLine(String.Format("Ensure that the key value '{0}' "
            + "matches the value of the '{1}' property.",
            order.EntityKey.EntityKeyValues[0].Value,
            order.EntityKey.EntityKeyValues[0].Key));
    }
    catch (UpdateException)
    {
        Console.WriteLine(String.Format("An error has occured. Ensure that "
        + "an object with an value of '{0}' for key property '{1}' exists.",
        order.EntityKey.EntityKeyValues[0].Value,
        order.EntityKey.EntityKeyValues[0].Key));
    }
}

The following example creates an instance of EntityKey using key values from a detached object. This key is then used to retrieve an attached instance of the object.

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 = Nothing

    Using advWorksContext As AdventureWorksEntities = _
        New AdventureWorksEntities()
        Try
            ' Create the detached object's entity key.
            key = advWorksContext.CreateEntityKey("SalesOrderDetail", updatedItem)

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

            advWorksContext.SaveChanges()
        Catch ex As InvalidOperationException
            Console.WriteLine(ex.ToString())
        End Try

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

    using (AdventureWorksEntities advWorksContext =
        new AdventureWorksEntities())
    {
        try
        {
            // Create the detached object's entity key.
            key = advWorksContext.CreateEntityKey("SalesOrderDetail", updatedItem);
            
            // Get the original item based on the entity key from the context
            // or from the database.
            if (advWorksContext.TryGetObjectByKey(key, out originalItem))
            {
                // Call the ApplyPropertyChanges method to apply changes
                // from the updated item to the original version.
                advWorksContext.ApplyPropertyChanges(
                    key.EntitySetName, updatedItem);
            }

            advWorksContext.SaveChanges();
        }
        catch (InvalidOperationException ex)
        {
            Console.WriteLine(ex.ToString());
        }
    }
}

See Also

Tasks

How to: Return a Specific Object Using its Key (Entity Framework)

Concepts

Object Services Overview (Entity Framework)