ObjectContext.TryGetObjectByKey(EntityKey, Object) 方法

定義

傳回具有指定之實體索引鍵的物件。

public:
 bool TryGetObjectByKey(System::Data::EntityKey ^ key, [Runtime::InteropServices::Out] System::Object ^ % value);
public bool TryGetObjectByKey (System.Data.EntityKey key, out object value);
member this.TryGetObjectByKey : System.Data.EntityKey * obj -> bool
Public Function TryGetObjectByKey (key As EntityKey, ByRef value As Object) As Boolean

參數

key
EntityKey

要尋找之物件的索引鍵。

value
Object

在這個方法傳回時,它會包含此物件。

傳回

如果擷取物件成功,則為 true。 如果 key 是暫存的、連接為 falsevaluenull,則為 null

例外狀況

key 的不相容中繼資料。

keynull

範例

此範例會為指定類型的實體建立 , 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.");
    }
}

備註

TryGetObjectByKey 會嘗試從 EntityKey 擷取具有指定之 ObjectStateManager 的物件。 如果此物件目前尚未載入物件內容中,系統就會執行查詢,以便嘗試從資料來源中傳回此物件。 如需詳細資訊,請參閱物件查詢

您可以使用 TryGetObjectByKey 方法來避免處理找不到此物件時,ObjectNotFoundException 所引發的 GetObjectByKey

這個方法將會傳回處於 Deleted 狀態中的物件。

暫存索引鍵無法用來從資料來源中傳回物件。

方法TryGetObjectByKey會套GetObjectByKey用 方法的標準 .NET TryParse 模式,在攔截 時ObjectNotFoundExceptionfalse回 。

適用於

另請參閱