Sugerir traducción
 
Otros han sugerido:

progress indicator
No hay más sugerencias.
Evaluar y enviar comentarios
Contraer todo/Expandir todo Contraer todo
Ver contenido:  en paraleloVer contenido: en paralelo
.NET Framework Class Library
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)
Visual Basic
<SerializableAttribute> _
<DataContractAttribute(IsReference := True)> _
Public NotInheritable Class EntityKey _
    Implements IEquatable(Of EntityKey)
C#
[SerializableAttribute]
[DataContractAttribute(IsReference = true)]
public sealed class EntityKey : IEquatable<EntityKey>
Visual C++
[SerializableAttribute]
[DataContractAttribute(IsReference = true)]
public ref class EntityKey sealed : IEquatable<EntityKey^>
F#
[<Sealed>]
[<SerializableAttribute>]
[<DataContractAttribute(IsReference = true)>]
type EntityKey =  
    class
        interface IEquatable<EntityKey>
    end

The EntityKey type exposes the following members.

  NameDescription
Public methodEntityKey()()()Initializes a new instance of the EntityKey class.
Public methodEntityKey(String, IEnumerable<(Of <(KeyValuePair<(Of <(String, Object>)>)>)>))Initializes a new instance of the EntityKey class with an entity set name and a generic KeyValuePair collection.
Public methodEntityKey(String, IEnumerable<(Of <(EntityKeyMember>)>))Initializes a new instance of the EntityKey class with an entity set name and an IEnumerable<(Of <(T>)>) collection of EntityKeyMember objects.
Public methodEntityKey(String, String, Object)Initializes a new instance of the EntityKey class with an entity set name and specific entity key pair.
Top
  NameDescription
Public propertyEntityContainerNameGets or sets the name of the entity container.
Public propertyEntityKeyValuesGets or sets the key values associated with this EntityKey.
Public propertyEntitySetNameGets or sets the name of the entity set.
Public propertyIsTemporaryGets a value that indicates whether the EntityKey is temporary.
Top
  NameDescription
Public methodEquals(EntityKey)Returns a value that indicates whether this instance is equal to a specified EntityKey.
Public methodEquals(Object)Returns a value that indicates whether this instance is equal to a specified object. (Overrides Object..::.Equals(Object).)
Protected methodFinalizeAllows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public methodGetEntitySetGets the entity set for this entity key from the given metadata workspace.
Public methodGetHashCodeServes 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 methodGetTypeGets the Type of the current instance. (Inherited from Object.)
Protected methodMemberwiseCloneCreates a shallow copy of the current Object. (Inherited from Object.)
Public methodOnDeserializedHelper method that is used to deserialize an EntityKey.
Public methodOnDeserializingHelper method that is used to deserialize an EntityKey.
Public methodToStringReturns a string that represents the current object. (Inherited from Object.)
Top
  NameDescription
Public operatorStatic memberEqualityCompares two EntityKey objects.
Public operatorStatic memberInequalityCompares two EntityKey objects.
Top
  NameDescription
Public fieldStatic memberEntityNotValidKeyA simple EntityKey identifying an entity that resulted from a failed TREAT operation.
Public fieldStatic memberNoEntitySetKeyA 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.

Visual Basic
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
C#
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.");
    }
}
Visual Basic
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
C#
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 Role not supported), Windows Server 2008 R2 (Server Core Role not supported), 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.
Biblioteca de clases de .NET Framework
EntityKey (Clase)

Proporciona una referencia duradera a un objeto que es una instancia de un tipo de entidad.

System..::.Object
  System.Data..::.EntityKey

Espacio de nombres:  System.Data
Ensamblado:  System.Data.Entity (en System.Data.Entity.dll)
Visual Basic
<SerializableAttribute> _
<DataContractAttribute(IsReference := True)> _
Public NotInheritable Class EntityKey _
    Implements IEquatable(Of EntityKey)
C#
[SerializableAttribute]
[DataContractAttribute(IsReference = true)]
public sealed class EntityKey : IEquatable<EntityKey>
Visual C++
[SerializableAttribute]
[DataContractAttribute(IsReference = true)]
public ref class EntityKey sealed : IEquatable<EntityKey^>
F#
[<Sealed>]
[<SerializableAttribute>]
[<DataContractAttribute(IsReference = true)>]
type EntityKey =  
    class
        interface IEquatable<EntityKey>
    end

El tipo EntityKey expone los siguientes miembros.

  NombreDescripción
Método públicoEntityKey()()()Inicializa una nueva instancia de la clase EntityKey.
Método públicoEntityKey(String, IEnumerable<(Of <(KeyValuePair<(Of <(String, Object>)>)>)>))Inicializa una nueva instancia de la clase EntityKey con un nombre de conjunto de entidades y una colección KeyValuePair genérica.
Método públicoEntityKey(String, IEnumerable<(Of <(EntityKeyMember>)>))Inicializa una nueva instancia de la clase EntityKey con un nombre de conjunto de entidades y una colección IEnumerable<(Of <(T>)>) de objetos EntityKeyMember.
Método públicoEntityKey(String, String, Object)Inicializa una nueva instancia de la clase EntityKey con un nombre de conjunto de entidades y un par de claves de entidad específico.
Arriba
  NombreDescripción
Propiedad públicaEntityContainerNameObtiene o establece el nombre del contenedor de entidades.
Propiedad públicaEntityKeyValuesObtiene o establece los valores de clave asociados al objeto EntityKey en cuestión.
Propiedad públicaEntitySetNameObtiene o establece el nombre del conjunto de entidades.
Propiedad públicaIsTemporaryObtiene un valor que indica si el objeto EntityKey es temporal.
Arriba
  NombreDescripción
Método públicoEquals(EntityKey)Devuelve un valor que indica si esta instancia es igual que un objeto EntityKey especificado.
Método públicoEquals(Object)Devuelve un valor que indica si esta instancia equivale a un objeto especificado. (Invalida a Object..::.Equals(Object)).
Método protegidoFinalizePermite que un objeto intente liberar recursos y realizar otras operaciones de limpieza antes de ser reclamado por la recolección de elementos no utilizados. (Se hereda de Object).
Método públicoGetEntitySetObtiene el conjunto de entidades para esta clave de entidad a partir del área de trabajo de metadatos especificada.
Método públicoGetHashCodeSirve como función hash para el objeto EntityKey actual. El método GetHashCode se puede utilizar en algoritmos hash y estructuras de datos, como una tabla hash. (Invalida a Object..::.GetHashCode()()()).
Método públicoGetTypeObtiene el objeto Type de la instancia actual. (Se hereda de Object).
Método protegidoMemberwiseCloneCrea una copia superficial del objeto Object actual. (Se hereda de Object).
Método públicoOnDeserializedMétodo auxiliar que se usa para deserializar un objeto EntityKey.
Método públicoOnDeserializingMétodo auxiliar que se usa para deserializar un objeto EntityKey.
Método públicoToStringDevuelve una cadena que representa el objeto actual. (Se hereda de Object).
Arriba
  NombreDescripción
Operador públicoMiembro estáticoEqualityCompara dos objetos EntityKey.
Operador públicoMiembro estáticoInequalityCompara dos objetos EntityKey.
Arriba
  NombreDescripción
Campo públicoMiembro estáticoEntityNotValidKeyUn objeto EntityKey simple que identifica una entidad que es el resultado de una operación TREAT en la que se ha producido un error.
Campo públicoMiembro estáticoNoEntitySetKeyObjeto EntityKey singleton por el que se identifica una entidad de solo lectura.
Arriba

Los objetos EntityKey son inmutables; es decir, una vez construidos, no se pueden modificar.

Para obtener más información, vea Working with Entity Keys (Entity Framework).

Estos ejemplos están basados en el Adventure Works Sales Model. En el ejemplo se muestra cómo crear y usar un objeto EntityKey.

Visual Basic
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
C#
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.");
    }
}
Visual Basic
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
C#
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

Compatible con: 4, 3.5 SP1

.NET Framework Client Profile

Compatible con: 4

Windows 7, Windows Vista SP1 o posterior, Windows XP SP3, Windows Server 2008 (no se admite Server Core), Windows Server 2008 R2 (se admite Server Core con SP1 o posterior), Windows Server 2003 SP2

.NET Framework no admite todas las versiones de todas las plataformas. Para obtener una lista de las versiones compatibles, vea Requisitos de sistema de .NET Framework.
Todos los miembros static (Shared en Visual Basic) públicos de este tipo son seguros para la ejecución de subprocesos. No se garantiza que los miembros de instancias sean seguros para la ejecución de subprocesos.
Contenido de la comunidad   ¿Qué es Community Content?
Agregar contenido nuevo RSS  Anotaciones
Processing
© 2012 Microsoft. Reservados todos los derechos. Términos de uso | Marcas Registradas | Privacidad
Page view tracker