ObjectContext.CreateEntityKey(String, Object) 方法

定義

建立特定物件的實體索引鍵,或傳回實體索引鍵 (如果已經存在的話)。

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

參數

entitySetName
String

此實體物件所屬之實體集的完整限定名稱。

entity
Object

要擷取其實體索引鍵的物件。

傳回

物件的 EntityKey

例外狀況

當任一個參數是 null 時。

entitySetName 是空的。

-或-

entity 物件的型別不存在於實體集時。

-或-

entitySetName 不完整時。

無法根據提供的參數成功建構實體索引鍵時。

範例

在這個範例中,CreateEntityKey 是用來擷取現有物件的實體索引鍵。

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

備註

EntityKey如果 不存在 , entity 方法 CreateEntityKey 會為其建立新的索引鍵。

這個方法是用來判斷具有相同 EntityKey 的物件是否已經附加至 ObjectContext。 如果已經附加具有相同 EntityKey 的物件,就會引發例外狀況。 您可以先使用 CreateEntityKey 方法來嘗試擷取已中斷連結物件的 EntityKey,然後再呼叫 Attach 方法。

適用於