Compartir a través de


Cómo: Enlazar controles a tipos derivados (Entity Framework)

Entity Framework permite enlazar controles de Windows Forms, como un ComboBox o un DataGridView a una EntityCollection. Sin embargo, al ejecutar el método OfType en una EntityCollection para devolver una colección de objetos de un tipo derivado, no puede enlazar directamente el elemento IEnumerable devuelto a un control. En el ejemplo siguiente se muestra cómo usar el método CreateSourceQuery para crear una ObjectQuery que defina la EntityCollection. Esta consulta se ejecuta con el método OfType para realizar el enlace a un subtipo concreto. Para obtener más información, vea Enlazar objetos a controles (Entity Framework).

El ejemplo de este tema se basa en una versión modificada del modelo School. Esta versión admite la herencia de tabla por tipo con Course como un tipo abstracto. Complete el tutorial Asignar la herencia de tabla por tipo para modificar el modelo School de forma que admita el ejemplo de la herencia de tabla por tipo usado en este tema.

Ejemplo

El ejemplo siguiente es de un formulario de Windows Forms. Cuando se carga el formulario, se devuelve un ObjectResult de objetos Department llamando al método Execute de ObjectQuery. Este resultado se enlaza a un cuadro combinado. Cuando se selecciona un pedido, se llama al método CreateSourceQuery en la clase relacionada EntityCollection de objetos Course. La instancia de ObjectQuery devuelta al ejecutar el método OfType y el resultado se enlaza a un control DataGridView. El tipo que se usa con el método OfType se establece basándose en el valor de un cuadro de opción del formulario.

using System;
using System.Collections.Generic;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.Objects;
using System.Data.Objects.DataClasses;

namespace Microsoft.Samples.Edm
{
    public partial class SchoolForm : Form
    {
        private SchoolEntities context;
        private bool isOnlineCourse = false;
        
        public SchoolForm()
        {
            // Initializes the designer-generated controls.
            InitializeComponent();

            if (isOnlineCourse) radioButtonOnline.Checked = true;
            else radioButtonOnsite.Checked = true;
        }


        private void SchoolForm_Load(object sender, EventArgs e)
        {
            // Initialize the object context.
            try
            {
                context = new SchoolEntities();

                // Create a query for all departments.
                ObjectQuery<Department> departmentQuery =
                    context.Departments;

                // Display the department name in the combo box.
                this.comboBoxDepartment.DisplayMember = "Name";

                // Bind the combo box to the ObjectResult of the departments 
                // that are returned when the query is executed.
                this.comboBoxDepartment.DataSource = 
                    departmentQuery.Execute(MergeOption.AppendOnly);
            }
            catch (EntitySqlException ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void BindToCourseByType()
        {
            // Get the currently selected Department object.
            Department selectedDepartment =
                (Department)this.comboBoxDepartment.SelectedItem;

            try
            {
                if (isOnlineCourse)
                {
                    // 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);
                }
                else
                {
                    // Bind the data grid to the result of the execution of the ObjectQuery 
                    // that returns only the on-site courses for the selected department.
                    dataGridViewCourses.DataSource =
                        selectedDepartment.Courses.CreateSourceQuery()
                        .OfType<OnsiteCourse>().Execute(MergeOption.AppendOnly);
                }

                // Hide the columns bound to navigation properties.
                dataGridViewCourses.Columns["Department"].Visible = false;
                dataGridViewCourses.Columns["StudentGrades"].Visible = false;
                dataGridViewCourses.Columns["People"].Visible = false;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        private void departmentComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.BindToCourseByType();
        }
        private void onlineRadio_CheckedChanged(object sender, EventArgs e)
        {
            if (this.radioButtonOnline.Checked)
            {
                isOnlineCourse = true;
                this.BindToCourseByType();
            }
            else
            {
                isOnlineCourse = false;
                this.BindToCourseByType();
            }
        }
        private void Close_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}

Vea también

Tareas

Cómo: Enlazar objetos a controles de Windows Presentation Foundation (Entity Framework)
Cómo: Enlazar objetos a controles de Windows Forms (Entity Framework)

Conceptos

Enlazar objetos a controles (Entity Framework)