キーを使用して特定のオブジェクトを返す方法 (Entity Framework)

このトピックでは、オブジェクト クエリを明示的に作成して実行する代わりに、エンティティをそのキー値で取得する方法について説明します。 The examples in this topic are based on the AdventureWorks Sales Model. これらの例のコードを実行するには、あらかじめプロジェクトに AdventureWorks Sales Model を追加し、Entity Framework が使用されるようにプロジェクトを構成しておく必要があります。 To do this, complete the procedures in Entity Framework プロジェクトを手動で構成する方法 and 方法: モデル ファイルとマッピング ファイルを手動で定義する (Entity Framework). Entity Data Model ウィザードを使用して、AdventureWorks Sales Model を定義することもできます。 詳細については、「Entity Data Model ウィザードを使用する方法 (Entity Framework)」を参照してください。

この例では、ObjectContextGetObjectByKey メソッドを使用し、オブジェクト コンテキストに対して EntityKey を指定することによって、対応するオブジェクトを取得します。 指定した EntityKey に対応する既存のエンティティが見つからなかった場合、ObjectNotFoundException が発生します。この例には、そのための例外処理も記述されています。 ObjectNotFoundException を防ぐには、TryGetObjectByKey を呼び出します。この場合、例外は生成されずに、false が返されます。

Using context As New AdventureWorksEntities()
    Try
        ' Define the entity key values. 
        Dim entityKeyValues As IEnumerable(Of KeyValuePair(Of String, Object)) = _
            New KeyValuePair(Of String, Object)() {New KeyValuePair(Of String, Object)("SalesOrderID", 43680)}

        ' Create the key for a specific SalesOrderHeader object. 
        Dim key As New EntityKey("AdventureWorksEntities.SalesOrderHeaders", entityKeyValues)

        ' Get the object from the context or the persisted store by its key. 
        Dim order As SalesOrderHeader = DirectCast(context.GetObjectByKey(key), SalesOrderHeader)

        Console.WriteLine("SalesOrderID: {0} Order Number: {1}", order.SalesOrderID, order.SalesOrderNumber)
    Catch ex As ObjectNotFoundException
        Console.WriteLine(ex.ToString())
    End Try
End Using
using (AdventureWorksEntities context =
    new AdventureWorksEntities())
{
    try
    {
        // Define the entity key values.
        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.
        SalesOrderHeader order =
            (SalesOrderHeader)context.GetObjectByKey(key);

        Console.WriteLine("SalesOrderID: {0} Order Number: {1}",
            order.SalesOrderID, order.SalesOrderNumber);
    }
    catch (ObjectNotFoundException ex)
    {
        Console.WriteLine(ex.ToString());
    }
}

参照

処理手順

方法: エンティティ型オブジェクトを返すクエリを実行する (Entity Framework)
方法: クエリ パスを使用して結果を構築する (Entity Framework)

概念

概念モデルに対するクエリ (Entity Framework)