Sdílet prostřednictvím


Binding Objects to Controls (Entity Framework)

Object Services enables you to bind controls such as ComboBox, ListView, and DataGridView controls to an EntityCollection or to an ObjectResult that is returned when an ObjectQuery is executed. Both Entity Framework classes implement the IListSource interface for data binding. All entity objects derive from the StructuralObject base class, which implements INotifyPropertyChanged. This enables two-way data binding between object properties and controls so that updates to controls propagate back to the properties of the bound object.

To bind objects to a Windows Form control, set the DataSource property of the control to the EntityCollection or to the ObjectResult that is returned when the Execute method is called on an ObjectQuery object. The following example binds an EntityCollection to a DataGridView control:

' 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;

For more information, see How to: Bind Objects to Windows Form Controls (Entity Framework).

You can create data sources that are based on your objects in a Visual Studio application. After you define an entity type as a data source in a project, you can create forms that display Entity Data Model (EDM) data by dragging items from the Data Sources window onto forms. These items become controls on the form that are bound to the data source. For more information, see Data Sources Window. At run time, you assign the result of a typed ObjectQuery to the DataSource property of the BindingSource that is used by the data source. This displays the properties of the objects that are returned by the query in the controls. Like with direct data binding, you apply updates made to the values of controls to the data source when you call the SaveChanges method. For more information, see How to: Add an Object as a Project Data Source (Entity Framework).

To bind objects to a Windows Presentation Foundation (WPF) control, set the DataContext property of the control to the EntityCollection or to the ObjectResult returned when the Execute method is called on an ObjectQuery object. Use the ItemsSource property to set the object source for the control. If you are binding a control to a related object that is returned by a navigation property, include the path in the binding defined for the ItemsSource property. This path is relative to the root object set by the DataContext property of the parent control. The following example sets the DataContext property of a Grid control to bind the control to an 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);

The following example shows the XAML binding definition of the child ListView and ComboBox controls:

<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>

For more information, see How to: Bind Objects to Windows Presentation Foundation Controls (Entity Framework).

The Entity Framework includes the EntityDataSource Web server control. You can use this ASP.NET data source control to bind the results of object queries to controls on an ASP.NET Web page. For more information, see the EntityDataSource control example.

The following considerations apply when binding objects to controls:

  • We recommend that you not bind controls directly to an ObjectQuery. Instead, bind controls to the result of the Execute method. Binding in this manner prevents a query from being executed multiple times during binding.

    The following example binds a ComboBox to the ObjectResult that is returned from executing an ObjectQuery of type SalesOrderHeader:

    ' 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")
    
    ' Display the PO number in the combo box.
    Me.ordersListBox.DisplayMember = "PurchaseOrderNumber"
    
    ' 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");
    
    // 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);
    
  • To ensure that the data source is up to date, you may need to execute the query again using the Execute method. This will bind the control to a new ObjectResult. You should do this to ensure that object data is up-to-date in the following cases:

    • Changes are being made to the same ObjectContext outside the bound control.

    • Changes are being made to data in the data source.

    • Objects were returned using the NoTracking option.

  • You can access individual entity objects from a control after data binding has occurred. However, you cannot access the collection from the bound control. For more information, see How to: Bind Objects to Windows Form Controls (Entity Framework).

  • You can bind an EntityCollection to a control because it implements IListSource. However, when you execute the OfType method on an EntityCollection to return a collection of objects of a derived type, you cannot bind the returned IEnumerable directly to a control. To bind a control to a collection of objects of a derived type obtained from an EntityCollection, instead use the CreateSourceQuery method to get the ObjectQuery that defines the base EntityCollection. You can bind a control to the execution of the ObjectQuery that is returned by the OfType method on an ObjectQuery, as in the following example:

    ' 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.Course.CreateSourceQuery() _
            .OfType(Of OnlineCourse)().Execute(MergeOption.AppendOnly)
    
    // 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.Course.CreateSourceQuery()
        .OfType<OnlineCourse>().Execute(MergeOption.AppendOnly);
    

    For more information, see How to: Bind Controls to Derived Types (Entity Framework)

See Also

Concepts

Projection and Restriction Methods (LINQ to Entities)

Other Resources

Working with Objects (Entity Framework)
Walkthrough: Creating the Course Manager Web Application