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 如果該物體成功回收。 false 若 為 key 暫時,則連接為 null,或 valuenull

例外狀況

的元資料不相容。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嘗試從 ObjectStateManager中擷取具有指定 EntityKey 的物件。 如果物件目前尚未載入到物件上下文中,會執行查詢,嘗試從資料來源回傳該物件。

使用此 TryGetObjectByKey 方法以避免在找不到物件時處理 ObjectNotFoundException raised by GetObjectByKey

此方法會回傳狀態下的 Deleted 物件。

暫存金鑰無法用來從資料來源回傳物件。

TryGetObjectByKey 方法對 GetObjectByKey 方法套用標準的 .NET TryParse 模式,當捕捉到 ObjectNotFoundException 時返回 false

適用於

另請參閱