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 は、指定した EntityKey を持つオブジェクトを ObjectStateManagerから取得しようとします。 オブジェクトが現在オブジェクト コンテキストに読み込まれていない場合は、データ ソースからオブジェクトを返そうとしてクエリが実行されます。

オブジェクトが見つからないときにGetObjectByKeyによって発生したObjectNotFoundExceptionの処理を回避するには、TryGetObjectByKey メソッドを使用します。

このメソッドは、 Deleted 状態のオブジェクトを返します。

一時キーを使用してデータ ソースからオブジェクトを返すことはできません。

TryGetObjectByKey メソッドは、GetObjectByKey メソッドに標準の .NET TryParse パターンを適用し、ObjectNotFoundException がキャッチされたときに false を返します。

適用対象

こちらもご覧ください