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

物件服務可讓您將控制項 (如 ComboBoxListViewDataGridView 控制項) 繫結至 EntityCollection,或繫結至執行 ObjectQuery 時所傳回的 ObjectResult。兩種 實體架構 類別都會針對資料繫結來實作 IListSource 介面。所有實體物件都是衍生自會實作 INotifyPropertyChangedStructuralObject 基底類別 (Base Class)。如此可啟用物件屬性與控制項之間的雙向資料繫結,好讓控制項的更新可散佈回繫結之物件的屬性。

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

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

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

您可以在 Visual Studio 應用程式中,建立以物件為基礎的資料來源。將實體類型定義為專案中的資料來源後,藉由拖曳 [資料來源] 視窗的項目到表單上,即可建立會顯示 Entity Data Model (EDM) 資料的表單。這些項目會成為表單上繫結至資料來源的控制項。如需詳細資訊,請參閱資料來源視窗。在執行階段,您要將具型別 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 = query.Execute(MergeOption.AppendOnly)
// Execute the query and bind the result to the OrderItems control.
this.orderItemsGrid.DataContext = 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=SalesOrderDetail}" 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)

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

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

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

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

    ' Create a query for orders that includes line items.
    Dim orderQuery As ObjectQuery(Of SalesOrderHeader) = _
    context.SalesOrderHeader _
            .Where("it.CustomerID = @customerId", _
            New ObjectParameter("customerId", customerId)) _
    .Include("SalesOrderDetail")
    
    ' Bind the combo box to the ObjectResult of SalesOrderHeader 
    ' that is returned when the query is executed.
    Me.ordersListBox.DataSource = orderQuery.Execute(MergeOption.AppendOnly)
    
    // Create a query for orders that includes line items.
    ObjectQuery<SalesOrderHeader> orderQuery = context.SalesOrderHeader
        .Where("it.CustomerID = @customerId", 
        new ObjectParameter("customerId", customerId))
        .Include("SalesOrderDetail");
    
    // 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 的執行。

另請參閱

概念

投影和限制方法 (LINQ to Entities)

其他資源

使用物件 (Entity Framework)
逐步解說:建立 Course Manager Web 應用程式