Binding Objects to Controls

The Entity Framework 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. The entity types generated by the Entity Framework tools implement 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.SalesOrderDetails;

For more information, see How to: Bind Objects to Windows Form Controls.

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 data from the Entity Framework 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.

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 = 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);

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

For more information, see How to: Bind Objects to Windows Presentation Foundation Controls.

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.

    Note

    If you prefer to work with LINQ queries, we recommend that you cast the result of the query to ObjectQuery and call the Execute method.

    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.
    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);
    
  • 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.

  • 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.Courses.CreateSourceQuery()
        .OfType<OnlineCourse>().Execute(MergeOption.AppendOnly);
    

    For more information, see How to: Bind Controls to Derived Types

In This Section

How to: Bind Objects to Windows Form Controls

How to: Bind Objects to Windows Presentation Foundation Controls

How to: Bind Controls to Derived Types

How to: Add an Object as a Project Data Source

See Also

Concepts

Working with Objects

Other Resources

Walkthrough: Creating the Class Schedule Web Application