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

Entity Framework 可讓您將控制項 (如 ComboBoxListViewDataGridView 控制項) 繫結至 EntityCollection,或繫結至執行 ObjectQuery 時所傳回的 ObjectResult。 兩種 Entity Framework 類別都會針對資料繫結來實作 IListSource 介面。 Entity Framework 工具產生的實體類型會實作 INotifyPropertyChanged。 如此可啟用物件屬性與控制項之間的雙向資料繫結,好讓控制項的更新可散佈回繫結之物件的屬性。

若要將物件繫結至 Windows Form 控制項,請將控制項的 DataSource 屬性設為 EntityCollection,或者是設為對 ObjectQuery 物件呼叫 Execute 方法時所傳回的 ObjectResult。 下列範例會將 EntityCollection 繫結到 DataGridView 控制項:

// Bind the items for this order to the DataGridView.
lineItemsDataGrid.DataSource = order.SalesOrderDetails;

如需詳細資訊,請參閱 HOW TO:將物件繫結到 Windows Form 控制項 (Entity Framework)

您可以在 Visual Studio 應用程式中,建立以物件為基礎的資料來源。 將實體類型定義為專案中的資料來源後,藉由拖曳 [資料來源] 視窗的項目到表單上,即可建立會顯示來自 Entity Framework 之資料的表單。 這些項目會成為表單上繫結至資料來源的控制項。 如需詳細資訊,請參閱Data Sources Window。 在執行階段,您要將具型別 ObjectQuery 的結果指派給資料來源所使用 BindingSourceDataSource 屬性。 這會顯示控制項中查詢所傳回物件的屬性。 就跟直接使用資料繫結一樣,您可以在呼叫 SaveChanges 方法時,將控制項值所進行的更新套用到資料來源。 如需詳細資訊,請參閱 HOW TO:將物件加入做為專案資料來源 (Entity Framework)

若要將物件繫結至 Windows Presentation Foundation (WPF) 控制項,請將控制項的 DataContext 屬性設為 EntityCollection,或者是設為對 ObjectQuery 物件呼叫 Execute 方法時所傳回的 ObjectResult。 請使用 ItemsSource 屬性設定控制項的物件來源。 如果要將控制項繫結至導覽屬性所傳回的相關物件,請在針對 ItemsSource 屬性定義的繫結中加入路徑。 這個路徑是相對於父控制項 DataContext 屬性所設定根物件的位置。 下列範例會設定 Grid 控制項的 DataContext 屬性,將控制項繫結到 ObjectResult

' Execute the query and bind the result to the OrderItems control.
Me.orderItemsGrid.DataContext = CType(query, ObjectQuery).Execute(MergeOption.AppendOnly)
// Execute the query and bind the result to the OrderItems control.
this.orderItemsGrid.DataContext = ((ObjectQuery)query).Execute(MergeOption.AppendOnly);

下列範例顯示子控制項 ListViewComboBox 的 XAML 繫結定義:

<ComboBox DisplayMemberPath="SalesOrderID" ItemsSource="{Binding}"
          IsSynchronizedWithCurrentItem="true" 
          Height="23" Margin="122,12,198,0" Name="comboBoxOrder" VerticalAlignment="Top"/>
<ListView ItemsSource="{Binding Path=SalesOrderDetails}" Name="listViewItems" Margin="34,46,34,50">
    <ListView.View>
        <GridView AllowsColumnReorder="False" ColumnHeaderToolTip="Line Items">
            <GridViewColumn DisplayMemberBinding="{Binding Path=ProductID}" 
                Header="Product" Width="50"/>
            <GridViewColumn DisplayMemberBinding="{Binding Path=OrderQty}" 
                Header="Quantity" Width="50"/>
            <GridViewColumn DisplayMemberBinding="{Binding Path=UnitPrice}" 
                Header="Cost" Width="50"/>
            <GridViewColumn DisplayMemberBinding="{Binding Path=LineTotal}" 
                Header="Line Total" Width="80"/>
        </GridView>
    </ListView.View>
</ListView>

如需詳細資訊,請參閱 HOW TO:將物件繫結到 Windows Presentation Foundation 控制項 (Entity Framework)

Entity Framework 包含 EntityDataSource Web 伺服器控制項。 您可以使用這個 ASP.NET 資料來源控制項,將物件查詢的結果繫結至 ASP.NET 網頁上的控制項。 如需詳細資訊,請參閱 EntityDataSource 控制項範例

下列考量適用於將物件繫結至控制項時:

  • 建議您不要將控制項直接繫結到 ObjectQuery, 最好是將它們繫結到 Execute 方法的結果。 這種繫結方式可以防止在繫結期間執行多次查詢。

    Bb738469.note(zh-tw,VS.100).gif注意:
    如果您想要使用 LINQ 查詢,建議您將查詢的結果轉換成 ObjectQuery 並且呼叫 Execute 方法。

    下列範例會將 ComboBox 繫結至執行 SalesOrderHeader 型別的 ObjectQuery 時所傳回的 ObjectResult

    // Create a query for orders that includes line items.
    ObjectQuery<SalesOrderHeader> orderQuery = context.SalesOrderHeaders
        .Where("it.CustomerID = @customerId", 
        new ObjectParameter("customerId", customerId))
        .Include("SalesOrderDetails");
    
    // Display the PO number in the combo box.
    this.ordersListBox.DisplayMember = "PurchaseOrderNumber";
    
    // Bind the combo box to the ObjectResult of SalesOrderHeader 
    // that is returned when the query is executed.
    this.ordersListBox.DataSource = orderQuery.Execute(MergeOption.AppendOnly);
    
  • 為了確保資料來源是最新的狀態,您可能需要使用 Execute 方法再次執行查詢。 這會將控制項繫結到新的 ObjectResult。 在下列情況下,您最好這麼做以確保物件資料是最新的狀態:

    • 在繫結的控制項外,對相同的 ObjectContext 進行變更。

    • 在資料來源中,對資料進行變更。

    • 物件是使用 NoTracking 選項傳回的。

  • 當發生資料繫結之後,您可以從控制項存取個別實體物件。 但是,您無法從繫結的控制項存取集合。 如需詳細資訊,請參閱 HOW TO:將物件繫結到 Windows Form 控制項 (Entity Framework)

  • 您可以將 EntityCollection 繫結至控制項,因為它會實作 IListSource。 然而,如果對 EntityCollection 執行 OfType 方法以傳回衍生型別物件的集合,則不能將傳回的 IEnumerable 直接繫結至控制項。 若要將控制項繫結到從 EntityCollection 取得的衍生型別物件的集合,請改用 CreateSourceQuery 方法取得用於定義基底 EntityCollectionObjectQuery。 控制項的繫結目標可以是在 ObjectQuery 上,經由 OfType 方法所傳回的 ObjectQuery 執行,如下列範例所示:

    // Bind the data grid to the result of the execution of the ObjectQuery 
    // that returns only the online courses for the selected department.
    dataGridViewCourses.DataSource =
        selectedDepartment.Courses.CreateSourceQuery()
        .OfType<OnlineCourse>().Execute(MergeOption.AppendOnly);
    

    如需詳細資訊,請參閱 HOW TO:將控制項繫結到衍生型別 (Entity Framework)

本節內容

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

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

HOW TO:將控制項繫結到衍生型別 (Entity Framework)

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

另請參閱

概念

使用物件

其他資源

Walkthrough: Creating the Class Schedule Web Application