This topic has not yet been rated - Rate this topic

EntityKey Class

Provides a durable reference to an object that is an instance of an entity type.

System.Object
  System.Data.EntityKey

Namespace:  System.Data
Assembly:  System.Data.Entity (in System.Data.Entity.dll)
[SerializableAttribute]
[DataContractAttribute(IsReference = true)]
public sealed class EntityKey : IEquatable<EntityKey>

The EntityKey type exposes the following members.

  Name Description
Public method EntityKey() Initializes a new instance of the EntityKey class.
Public method EntityKey(String, IEnumerable<KeyValuePair<String, Object>>) Initializes a new instance of the EntityKey class with an entity set name and a generic KeyValuePair collection.
Public method EntityKey(String, IEnumerable<EntityKeyMember>) Initializes a new instance of the EntityKey class with an entity set name and an IEnumerable<T> collection of EntityKeyMember objects.
Public method EntityKey(String, String, Object) Initializes a new instance of the EntityKey class with an entity set name and specific entity key pair.
Top
  Name Description
Public property EntityContainerName Gets or sets the name of the entity container.
Public property EntityKeyValues Gets or sets the key values associated with this EntityKey.
Public property EntitySetName Gets or sets the name of the entity set.
Public property IsTemporary Gets a value that indicates whether the EntityKey is temporary.
Top
  Name Description
Public method Equals(EntityKey) Returns a value that indicates whether this instance is equal to a specified EntityKey.
Public method Equals(Object) Returns a value that indicates whether this instance is equal to a specified object. (Overrides Object.Equals(Object).)
Protected method Finalize Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method GetEntitySet Gets the entity set for this entity key from the given metadata workspace.
Public method GetHashCode Serves as a hash function for the current EntityKey object. GetHashCode is suitable for hashing algorithms and data structures such as a hash table. (Overrides Object.GetHashCode().)
Public method GetType Gets the Type of the current instance. (Inherited from Object.)
Protected method MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.)
Public method OnDeserialized Helper method that is used to deserialize an EntityKey.
Public method OnDeserializing Helper method that is used to deserialize an EntityKey.
Public method ToString Returns a string that represents the current object. (Inherited from Object.)
Top
  Name Description
Public operator Static member Equality Compares two EntityKey objects.
Public operator Static member Inequality Compares two EntityKey objects.
Top
  Name Description
Public field Static member EntityNotValidKey A simple EntityKey identifying an entity that resulted from a failed TREAT operation.
Public field Static member NoEntitySetKey A singleton EntityKey by which a read-only entity is identified.
Top

The EntityKey objects are immutable; that is, after they are constructed they cannot be modified.

For more information, see Working with Entity Keys (Entity Framework).

These examples are based on the Adventure Works Sales Model. The examples show you how to create and use an EntityKey.


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.");
    }
}



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);
    }
}


.NET Framework

Supported in: 4, 3.5 SP1

.NET Framework Client Profile

Supported in: 4

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Did you find this helpful?
(1500 characters remaining)
Community Content Add
Annotations FAQ