ObjectContext.CreateEntityKey(String, Object) Método

Definição

Cria a chave da entidade para um objeto específico ou retorna a chave da entidade se ela já existe.Creates the entity key for a specific object, or returns the entity key if it already exists.

public:
 System::Data::EntityKey ^ CreateEntityKey(System::String ^ entitySetName, System::Object ^ entity);
public System.Data.EntityKey CreateEntityKey (string entitySetName, object entity);
member this.CreateEntityKey : string * obj -> System.Data.EntityKey
Public Function CreateEntityKey (entitySetName As String, entity As Object) As EntityKey

Parâmetros

entitySetName
String

O nome totalmente qualificado do conjunto de entidades ao qual o objeto de entidade pertence.The fully qualified name of the entity set to which the entity object belongs.

entity
Object

O objeto para o qual a chave da entidade está sendo recuperada.The object for which the entity key is being retrieved.

Retornos

EntityKey

O EntityKey do objeto.The EntityKey of the object.

Exceções

Quando um parâmetro é null.When either parameter is null.

Quando entitySetName está vazio.When entitySetName is empty.

- ou --or-

Quando o tipo do objeto entity não existe no conjunto de entidades.When the type of the entity object does not exist in the entity set.

- ou --or-

Quando o entitySetName não é totalmente qualificado.When the entitySetName is not fully qualified.

Quando a chave da entidade não puder ser construída com êxito com base nos parâmetros fornecidos.When the entity key cannot be constructed successfully based on the supplied parameters.

Exemplos

O exemplo neste tópico é baseado no Microsoft SQL Server exemplos de produto: banco de dados.The example in this topic is based on the Microsoft SQL Server Product Samples: Database. Neste exemplo, CreateEntityKey é usado para recuperar a chave de entidade de um objeto existente.In this example, CreateEntityKey is used to retrieve the entity key of an existing object.

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

Comentários

Se EntityKey não houver um entity , o CreateEntityKey método criará uma nova chave para ele.If an EntityKey does not exist for the entity, the CreateEntityKey method creates a new key for it.

Esse método é usado para determinar se um objeto que tem o mesmo EntityKey já está anexado ao ObjectContext .This method is used to determine whether an object that has the same EntityKey is already attached to the ObjectContext. Se um objeto que tem o mesmo EntityKey já estiver anexado, uma exceção será gerada.If an object that has the same EntityKey is already attached, an exception is raised. Use o CreateEntityKey método para tentar recuperar o EntityKey do objeto desanexado antes de chamar o Attach método.Use the CreateEntityKey method to try to retrieve the EntityKey of the detached object before calling the Attach method.

Aplica-se a