コントロールを派生型にバインドする方法 (Entity Framework)

Entity Framework を使用すると、ComboBoxDataGridView などの Windows フォーム コントロールを EntityCollection にバインドできます。 ただし、EntityCollectionOfType メソッドを実行して派生型のオブジェクトのコレクションを返す場合は、返された IEnumerable をコントロールに直接バインドできません。 このトピックの例では、CreateSourceQuery メソッドを使用して、EntityCollection を定義する ObjectQuery を作成する方法を示します。 このクエリは、特定のサブタイプへのバインドを実行する OfType メソッドで実行されます。 詳細については、「コントロールへのオブジェクトのバインド (Entity Framework)」を参照してください。

このトピックの例は、「School モデル」の変更版に基づきます。 この変更版では、抽象型として Course での table-per-type 継承をサポートします。 「Table-Per-Type 継承のマッピング」チュートリアルを完了して、このトピックで使用されている table-per-type 継承の例をサポートできるよう School モデルを変更してください。

次の例は、Windows フォームからの抜粋です。 When the form is loaded, an ObjectResult of Department objects is returned by calling the Execute method of the ObjectQuery. この結果は、コンボ ボックスにバインドされます。 注文が選択されると、CreateSourceQuery メソッドが、Course オブジェクトの関連する EntityCollection に呼び出されます。 返される ObjectQuery は、OfType メソッドを使用して実行されたものであり、結果は DataGridView コントロールにバインドされます。 OfType メソッドで使用される型は、フォームのラジオボックス設定に基づいて設定されます。

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

参照

処理手順

オブジェクトを Windows Presentation Foundation コントロールにバインドする方法 (Entity Framework)
オブジェクトを Windows フォーム コントロールにバインドする方法 (Entity Framework)

概念

コントロールへのオブジェクトのバインド (Entity Framework)