Share via


查詢實體和關聯 (Entity Framework 快速入門)

在這項工作中,您將針對代表 School 模型中之實體 (Entity) 和關聯的 CLR 物件建立強型別 (Strongly Typed) 查詢,並且將顯示控制項繫結至從這些查詢傳回的物件集合。

查詢 School 資料庫中的部門

  1. CourseViewer 表單的程式碼檔案開頭,加入下列 using (C#) 或 Imports (Visual Basic) 陳述式 (Statement),以便參考根據 School 資料庫所建立的模型以及實體命名空間 (Namespace)。

    Imports System.Data.Objects
    Imports System.Data.Objects.DataClasses
    
    using System.Data.Objects;
    using System.Data.Objects.DataClasses;
    
  2. CourseViewer 表單的部分類別定義頂端,加入下列可建立 ObjectContext 執行個體 (Instance) 的程式碼。

    ' Create an ObjectContext instance based on SchoolEntity.
    Private schoolContext As SchoolEntities
    
    //Create an ObjectContext instance based on SchoolEntity
    private SchoolEntities schoolContext;
    
  3. CourseViewer 表單設計工具中,按兩下 CourseViewer 表單。

    這樣會開啟表單的字碼頁 (Code Page) 並且建立 courseViewer _Load 事件處理常式方法。

  4. courseViewer _Load 事件處理常式方中,複製並貼上下列可定義 DataGridView 的程式碼、執行可傳回部門集合 (按照 Name 排列順序) 的查詢,然後將 Department 物件的集合繫結至 departmentList 控制項。

    ' Initialize the ObjectContext.
    schoolContext = New SchoolEntities()
    
    ' Define a query that returns all Department objects
    ' and related Course objects, ordered by name.
    Dim departmentQuery As ObjectQuery(Of Department) = _
        From d In schoolContext.Departments.Include("Courses") _
        Order By d.Name _
        Select d
    Try
        ' Bind the ComboBox control to the query.
        ' To prevent the query from being executed multiple times during binding, 
        ' it is recommended to bind controls to the result of the Execute method. 
        Me.departmentList.DisplayMember = "Name"
        Me.departmentList.DataSource = CType(departmentQuery, ObjectQuery).Execute(MergeOption.AppendOnly)
    Catch ex As Exception
        MessageBox.Show(ex.Message)
    End Try
    
    //Initialize the ObjectContext
    schoolContext = new SchoolEntities();
    
    // Define a query that returns all Department  
    // objects and course objects, ordered by name.
    var departmentQuery = from d in schoolContext.Departments.Include("Courses")
                          orderby d.Name
                          select d;
    try
    {
        // Bind the ComboBox control to the query, 
        // which is executed during data binding.
        // To prevent the query from being executed multiple times during binding, 
        // it is recommended to bind controls to the result of the Execute method. 
        this.departmentList.DisplayMember = "Name";
        this.departmentList.DataSource = ((ObjectQuery)departmentQuery).Execute(MergeOption.AppendOnly);
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
    

顯示所選取部門的課程

  1. CourseViewer 表單設計工具中,按兩下 departmentList 控制項。

    這樣會建立 departmentList_SelectedIndexChanged 事件處理常式方法。

  2. 貼上下列用來載入與所選取部門相關之課程的程式碼。

    Try
        ' Get the object for the selected department.
        Dim department As Department = _
            CType(Me.departmentList.SelectedItem, Department)
    
        ' 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 ex As Exception
        MessageBox.Show(ex.Message)
    End Try
    
        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);
        }
    

後續步驟

您已成功建立可傳回 DepartmentCourse 物件的查詢,並且將這些物件繫結至控制項。接下來,請將您對資料格中 Course 物件做的變更儲存回資料庫:插入及更新資料 (Entity Framework 快速入門)

另請參閱

概念

處理實體資料

其他資源

範例 (Entity Framework)
Object Services (Entity Framework)