Compartilhar via


EntityKey Classe

Definição

Fornece uma referência durável a um objeto que é uma instância de um tipo de entidade.

public ref class EntityKey sealed : IEquatable<System::Data::EntityKey ^>
[System.Runtime.Serialization.DataContract(IsReference=true)]
[System.Serializable]
public sealed class EntityKey : IEquatable<System.Data.EntityKey>
[<System.Runtime.Serialization.DataContract(IsReference=true)>]
[<System.Serializable>]
type EntityKey = class
    interface IEquatable<EntityKey>
Public NotInheritable Class EntityKey
Implements IEquatable(Of EntityKey)
Herança
EntityKey
Atributos
Implementações

Exemplos

Estes exemplos mostram como criar e usar um 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 occurred. Ensure that an object with the '{0}' key value exists.",
        orderId);
    }
}

Comentários

Os EntityKey objetos são imutáveis; ou seja, depois de construídos, eles não podem ser modificados.

Construtores

Nome Description
EntityKey()

Inicializa uma nova instância da classe EntityKey.

EntityKey(String, IEnumerable<EntityKeyMember>)

Inicializa uma nova instância da EntityKey classe com um nome de conjunto de entidades e uma IEnumerable<T> coleção de EntityKeyMember objetos.

EntityKey(String, IEnumerable<KeyValuePair<String,Object>>)

Inicializa uma nova instância da EntityKey classe com um nome de conjunto de entidades e uma coleção genérica KeyValuePair .

EntityKey(String, String, Object)

Inicializa uma nova instância da EntityKey classe com um nome de conjunto de entidades e um par de chaves de entidade específico.

Campos

Nome Description
EntityNotValidKey

Uma simples EntityKey identificação de uma entidade resultante de uma operação TREAT com falha.

NoEntitySetKey

Um singleton EntityKey pelo qual uma entidade somente leitura é identificada.

Propriedades

Nome Description
EntityContainerName

Obtém ou define o nome do contêiner de entidade.

EntityKeyValues

Obtém ou define os valores de chave associados a isso EntityKey.

EntitySetName

Obtém ou define o nome do conjunto de entidades.

IsTemporary

Obtém um valor que indica se o EntityKey valor é temporário.

Métodos

Nome Description
Equals(EntityKey)

Retorna um valor que indica se essa instância é igual a uma especificada EntityKey.

Equals(Object)

Retorna um valor que indica se essa instância é igual a um objeto especificado.

GetEntitySet(MetadataWorkspace)

Obtém o conjunto de entidades para essa chave de entidade do workspace de metadados fornecido.

GetHashCode()

Serve como uma função de hash para o objeto atual EntityKey . GetHashCode() é adequado para algoritmos de hash e estruturas de dados, como uma tabela de hash.

GetType()

Obtém o Type da instância atual.

(Herdado de Object)
MemberwiseClone()

Cria uma cópia superficial do Objectatual.

(Herdado de Object)
OnDeserialized(StreamingContext)

Método auxiliar usado para desserializar um EntityKey.

OnDeserializing(StreamingContext)

Método auxiliar usado para desserializar um EntityKey.

ToString()

Retorna uma cadeia de caracteres que representa o objeto atual.

(Herdado de Object)

Operadores

Nome Description
Equality(EntityKey, EntityKey)

Compara dois objetos EntityKey.

Inequality(EntityKey, EntityKey)

Compara dois objetos EntityKey.

Aplica-se a