在本任务中,您将针对在 School 模型中表示实体和关联的 CLR 对象创建强类型查询,并将显示控件绑定到从这些查询中返回的对象集合。

在 School 数据库中查询系

  1. Imports (Visual Basic) 语句,以引用从 School 数据库和实体命名空间中创建的模型。

    using System.Data.Objects;

                        using System.Data.Objects.DataClasses;
     
  2. ObjectContext 实例的代码。

    //Create an ObjectContext instance based on SchoolEntityprivate        SchoolEntities schoolContext;
  3. CourseViewer 窗体。
  4. courseViewer _Load 事件处理程序方法。

  5. Department 对象的集合绑定到 departmentList 控件。

    //Initialize the ObjectContext
    schoolContext = new SchoolEntities();


                        // Define a query that returns all Department

显示所选系的课程

  1. departmentList 控件。

    departmentList_SelectedIndexChanged 事件处理程序方法。

  2. 粘贴以下用于加载与所选系相关的课程的代码。

    try
                {
                   
                        //Get the object for the selected department.
                    Department department = (Department)
                        this.departmentList.SelectedItem;

                   
                        //Bind the grid view to the collection of Course objects// that are related to the selected Department object.
                    courseGridView.DataSource = department.Courses;

                   
                        // Hide the columns that are bound to the navigation properties on Course.
                    courseGridView.Columns[
                        "Department"].Visible =
                        false;
                    courseGridView.Columns[
                        "StudentGrades"].Visible =
                        false;
                    courseGridView.Columns[
                        "OnlineCourse"].Visible =
                        false;
                    courseGridView.Columns[
                        "OnsiteCourse"].Visible =
                        false;
                    courseGridView.Columns[
                        "People"].Visible =
                        false;
                    courseGridView.Columns[
                        "DepartmentId"].Visible =
                        false;

                    courseGridView.AllowUserToDeleteRows =
                        false;
            courseGridView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
                }
               
                        catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
    后续步骤

插入和更新数据(实体框架快速入门)

请参见

概念

其他资源

相关文章: