Share via


HOW TO:將物件加入做為專案資料來源 (Entity Framework)

您可以在 Visual Studio 應用程式中,建立以物件為基礎的資料來源。 將實體類型定義為專案中的資料來源後,藉由將 [資料來源] 視窗的項目拖曳到表單上,即可建立會顯示實體資料的表單。 這些項目會成為表單上繫結至資料來源的控制項。 如需詳細資訊,請參閱將物件與控制項繫結 (Entity Framework)

在本主題中,您將為 Adventure Works Sales Model 中的 SalesOrderHeader 型別建立資料來源。 然後使用這個資料來源建立 Windows Form,其中的控制項會繫結至實體資料。 若要完成這些程序,您必須已經將 AdventureWorks Sales Model 加入到專案中,並設定您的專案使用 Entity Framework 。 若要這樣做,請完成 HOW TO:使用實體資料模型精靈 (Entity Framework) 中的程序。

建立以 SalesOrderHeader 類型為基礎的資料來源

  1. 如果您剛加入 Entity Data Model 項目,請建置專案。

  2. 按一下 [資料] 功能表上的 [加入新資料來源]。

  3. 在 [選擇資料來源類型] 頁面中,選取 [物件]。

  4. 在 [選取您要繫結的目標物件] 頁面中,依序展開專案節點和專案的命名空間節點,然後在樹狀檢視中選取 SalesOrderHeader 類型。

  5. 按一下 [完成]。

    SalesOrderHeader 資料來源就會加入到 [資料來源] 視窗。

在 Windows Form 中加入資料來源繫結控制項

  1. 在 [資料來源] 視窗中,展開 SalesOrderHeader 節點。

  2. SalesOrderHeader 節點拖曳一個或多個屬性到表單上。

    這會在表單上建立 salesOrderHeaderBindingSourcesalesOrderHeaderBindingNavigator 控制項。 表單上也會針對每個屬性建立資料繫結控制項,並伴隨著標示適當的標籤控制項。

  3. 拖曳 SalesOrderDetail 導覽屬性到表單上。

  4. 這會建立 salesOrderDetailBindingSource 控制項,且控制項的 DataSource 屬性設為 salesOrderHeaderBindingSourceDataMember 屬性設為 SalesOrderDetail。 表單上也會建立 salesOrderDetailDataGridView 資料繫結控制項,並伴隨著標示適當的標籤控制項。

若要將資料來源繫結到物件查詢的結果

  1. 開啟表單的字碼頁並加入下列 using 陳述式 (在 Visual Basic 中為 Imports):

    using System.Data.Objects;
    
  2. 在定義表單的部分類別中,加入下列可建立 ObjectContext 執行個體並定義 customerID 常數的程式碼。

    private AdventureWorksEntities context;
    private const int customerId = 277;
    
  3. 在表單設計工具中,按兩下表單。

    這樣會開啟表單的字碼頁,並且建立用於處理表單之 Load 事件的方法。

  4. Load 事件處理常式中,複製並貼入下列程式碼。

    // Initialize the object context.
    context = new AdventureWorksEntities();
    
    try
    {
        // Create a query for orders and related items.
        var orderQuery = context.SalesOrderHeaders
            .Where("it.CustomerID = @customerId",
            new ObjectParameter("customerId", customerId))
            .Include("SalesOrderDetails");
    
        // Set the data source of the binding source to the ObjectResult 
        // returned when the query is executed.
        salesOrderHeaderBindingSource.DataSource = 
            orderQuery.Execute(MergeOption.AppendOnly);
    }
    catch (EntitySqlException ex)
    {
        MessageBox.Show(ex.Message);
    }
    

    這個程式碼執行的查詢會傳回特定客戶的 SalesOrderHeader 集合和相關 SalesOrderDetail 物件,並將 SalesOrderHeader 物件集合繫結到 salesOrderHeaderBindingSource

另請參閱

工作

HOW TO:將物件繫結到 Windows Presentation Foundation 控制項 (Entity Framework)
HOW TO:將物件繫結到 Windows Form 控制項 (Entity Framework)

概念

將物件與控制項繫結 (Entity Framework)