Procedura: associare controlli a tipi derivati (Entity Framework)

Entity Framework consente di associare controlli Windows Form quali ComboBox o DataGridView a un oggetto EntityCollection. Quando, tuttavia, si esegue il metodo OfType su un EntityCollection per restituire una raccolta di oggetti di un tipo derivato, non è possibile associare l'oggetto restituito IEnumerable direttamente a un controllo. Nell'esempio in questo argomento viene mostrato come utilizzare il metodo CreateSourceQuery per creare un oggetto ObjectQuery che definisce EntityCollection. Questa query viene eseguita con il metodo OfType per eseguire l'associazione a un sottotipo specifico. Per ulteriori informazioni, vedere Associazione di oggetti ai controlli (Entity Framework).

L'esempio in questo argomento è basato su una versione modificata del modello School. Questa versione supporta l'ereditarietà tabella per tipo con Course come tipo astratto. Completare la procedura dettagliata Ereditarietà del mapping (Tabella per tipo) per modificare il modello School per supportare l'esempio di ereditarietà tabella per tipo utilizzato in questo argomento.

Esempio

L'esempio seguente deriva da un Windows Form. Quando il form viene caricato, viene restituita una classe ObjectResult di oggetti Department chiamando il metodo Execute di ObjectQuery. Questo risultato è associato a una casella combinata. Quando viene selezionato un ordine, il metodo CreateSourceQuery viene chiamato sull'oggetto EntityCollection correlato degli oggetti Course. L'oggetto ObjectQuery restituito eseguito utilizzando il metodo OfType e il risultato sono associati a un controllo DataGridView. Il tipo che viene utilizzato con il metodo OfType è impostato in base all'impostazione di una casella di opzione nel form.

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();
        }
    }
}

Vedere anche

Attività

Procedura: associare oggetti a controlli Windows Presentation Foundation (Entity Framework)
Procedura: associare oggetti a controlli Windows Form (Entity Framework)

Concetti

Associazione di oggetti ai controlli (Entity Framework)