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

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

範例

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

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());
    }
}

另請參閱

工作

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

概念

查詢概念模型 (Entity Framework)