共用方式為


HOW TO:使用特定物件的索引鍵傳回此物件 (Entity Framework)

本主題將示範如何使用索引鍵值來擷取實體 (Entity),而非明確建立和執行物件查詢。本主題的範例是根據 AdventureWorks Sales Model (EDM)。若要執行這些範例中的程式碼,請將 AdventureWorks Sales Model 加入到專案中,並將專案設定成使用 實體架構。若要這樣做,請完成 HOW TO:手動設定 Entity Framework 專案HOW TO:以手動方式定義 Entity Data Model (Entity Framework) 中的程序。您也可以使用 [Entity Data Model 精靈] 定義 AdventureWorks Sales Model。如需詳細資訊,請參閱 HOW TO:使用 Entity Data Model 精靈 (Entity Framework)

範例

這個範例會針對 ObjectContext 使用 GetObjectByKey 方法,將含有指定之 EntityKey 的物件傳入物件內容中。這個範例會處理當提供的 EntityKey 沒有對應至現有實體時所發生的 ObjectNotFoundException。若要避免 ObjectNotFoundException,請呼叫 TryGetObjectByKey,它會傳回 false 而非引發例外狀況 (Exception)。

Using advWorksContext 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.SalesOrderHeader", entityKeyValues)

        Dim order As SalesOrderHeader = _
            CType(advWorksContext.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 advWorksContext =
    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.SalesOrderHeader", entityKeyValues);

        // Get the object from the context or the persisted store by its key.
        SalesOrderHeader order =
            (SalesOrderHeader)advWorksContext.GetObjectByKey(key);

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

另請參閱

工作

HOW TO:執行傳回實體類型的查詢 (Entity Framework)
HOW TO:使用查詢路徑來設定結果外觀 (Entity Framework)

概念

以物件形式查詢資料 (Entity Framework)

其他資源

查詢 Entity Data Model (Entity Framework 工作)