ObjectContext.CreateEntityKey(String, Object) Metodo

Definizione

Crea la chiave di entità per un oggetto specifico o restituisce la chiave di entità se già esiste.

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

Parametri

entitySetName
String

Nome completo del set di entità a cui appartiene l'oggetto entità.

entity
Object

Oggetto per il quale viene recuperata la chiave di entità.

Restituisce

EntityKey dell'oggetto.

Eccezioni

Quando uno dei parametri è null.

Se entitySetName è vuoto.

-oppure-

Quando il tipo dell'oggetto entity non è presente nel set di entità.

-oppure-

Quando il parametro entitySetName non è completo.

Quando la chiave di entità non può essere costruita correttamente in base ai parametri specificati.

Esempio

In questo esempio viene utilizzato il metodo CreateEntityKey per recuperare la chiave di entità di un oggetto esistente.

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

Commenti

Se un oggetto EntityKey non esiste per entity, il CreateEntityKey metodo crea una nuova chiave.

Questo metodo viene utilizzato per determinare se un oggetto contenente lo stesso oggetto EntityKey è già connesso a ObjectContext. Se un oggetto contenente lo stesso oggetto EntityKey è già connesso, viene generata un'eccezione. Utilizzare il metodo CreateEntityKey per tentare di recuperare l'oggetto EntityKey dell'oggetto disconnesso prima di chiamare il metodo Attach.

Si applica a