逐步解說:使用預存程序擷取實體類型

本主題示範如何使用預存程序 (Stored Procedure) 擷取實體類型的集合。在本逐步解說中,您將會使用 ADO.NET 實體資料模型設計工具 (Entity Designer) 匯入預存程序,並且建立一個傳回實體類型集合的 Function Import

在 Entity Data Model (EDM) 中包含預存程序可讓您從應用程式程式碼呼叫該預存程序。當預存程序加入至概念模型時,就會呼叫 Function ImportFunction Import 會傳回簡單型別或實體類型的集合,或是沒有值傳回。

Cc716672.note(zh-tw,VS.100).gif注意:
為了使 Function Import 傳回 EntityType,由對應預存程序傳回的資料行必須完全符合傳回的 EntityType 的屬性。

[Entity Data Model 精靈] 從資料庫產生 EDM 時,會為資料庫的每個預存程序在儲存體模型中建立項目。對應項目會在 Function Import 建立時加入至概念模型。如需建立 Function Import 的詳細資訊,請參閱 HOW TO:匯入預存程序

必要條件

若要完成本逐步解說,必須建置 CourseManager 應用程式。如需詳細資訊和指示,請參閱 Entity Framework 快速入門。在建置此應用程式之後,您必須根據 GetStudentGrades 預存程序建立 Function Import,藉以修改其 EDM。

Cc716672.note(zh-tw,VS.100).gif注意:
因為本說明文件的許多逐步解說主題都從使用 CourseManager 應用程式開始,我們建議您為本逐步解說使用 CourseManager 應用程式的複本,而非編輯原始的 CourseManager 程式碼。

本逐步解說假設讀者具備以下基本能力:Visual Studio 和 .NET Framework 的使用能力,以及 Visual C# 或 Visual Basic 程式設計的能力。

建立 Function Import

在這個程序中,您將根據 GetStudentGrades 預存程序 (包含於 CourseManager EDM 的儲存體模型中) 建立 Function Import

若要建立 Function Import

  1. 在 Visual Studio 中開啟 CourseManager 方案。

  2. 按兩下 [方案總管] 中的 School.edmx 檔案。

    School.edmx 檔案隨即在 ADO.NET 實體資料模型設計工具 (Entity Designer) 中開啟,而且 [模型瀏覽器] 視窗也隨即開啟。

  3. 展開 [模型瀏覽器] 視窗中的 [EntityContainer: SchoolEntities] 節點。

    [Entity Sets]、[Association Sets] 和 [Function Imports] 資料夾隨即在樹狀檢視中顯示。

  4. 以滑鼠右鍵按一下 [Function Imports] 並選取 [建立 Function Import]。

    [New Function Import] 對話方塊隨即開啟。

  5. 從 [預存程序名稱] 下拉式清單中選取 GetStudentGrades

  6. 在 [Function Import 名稱]] 文字方塊中輸入 GetStudentGrades

  7. 從 [傳回型別] 下拉式清單中選取 CourseGrade

    Cc716672.note(zh-tw,VS.100).gif注意:
    我們可以把傳回型別設為 CourseGrade,因為由 GetStudentGrades 預存程序 (EnrollementIDGrade) 傳回的資料行完全符合 CourseGrade 實體類型的純量屬性。

  8. 按一下 [確定]。

    GetStudentGrades Function Import 隨即加入至 EDM。

建構使用者介面

在這個程序中,您將新增 CourseManager 應用程式的使用者介面,以便可以檢視所選學生的成績。

若要建構使用者介面

  1. 以滑鼠右鍵按一下 [方案總管] 中的 CourseManager 專案,然後指向 [加入],再選取 [新增項目]。

    [加入新項目] 對話方塊隨即出現。

  2. 選取 [Windows Form],然後將表單的名稱設為 GradeViewer.vb 或 GradeViewer.cs,再按一下 [加入]。

    新的表單隨即加入至專案並在表單設計工具中開啟。這個表單的名稱已設為 GradeViewer,而且文字已設為 GradeViewer

  3. ComboBox 控制項從 [工具箱] 拖曳至表單,並在 [屬性] 視窗中將它的 [Name] 設為 studentList

  4. DataGridView 控制項從 [工具箱] 拖曳至表單,並在 [屬性] 視窗中將它的 [Name] 設為 gradeGridView

  5. 按兩下 [方案總管] 中的 CourseViewer.vbCourseViewer.cs 檔案。

    該檔案隨即在表單設計工具中開啟。

  6. Button 控制項拖曳至表單。將它的 [Name] 設為 viewGrades,以及它的 [Text] 設為 ViewGrades

  7. 按兩下 viewGradesButton 控制項。

    viewGrades_Click 事件處理常式會加入至程式碼後置 (Code-Behind) 的檔案。

  8. 將下列程式碼加入至 viewGrades_Click 事件處理常式:

    Dim gradeViewer As New GradeViewer()
    gradeViewer.Visible = True
    
    GradeViewer gradeViewer = new GradeViewer();
    gradeViewer.Visible = true;
    

現已完成使用者介面。

使用預存程序擷取實體類型

在這個程序中,您將建立程式碼,用它來執行先前從 GetStudentGrades 預存程序建立的 Function Import。然後,此程式碼會將傳回的 EntityType 集合繫結至 DataGridView 控制項。如需將物件繫結至控制項的詳細資訊,請參閱Binding Objects to Controls (Entity Framework)

若要使用預存程序擷取實體類型

  1. 表單設計工具中已開啟 GradeViewer 表單時,按兩下表單的主體。

    GradeViewer 表單之程式碼後置的檔案隨即開啟。

  2. 加入下列 using (C#) 或 Imports (Visual Basic) 陳述式:

    Imports System.Data.Objects
    Imports System.Data.Objects.DataClasses
    
    using System.Data.Objects;
    using System.Data.Objects.DataClasses;
    
  3. 將屬性加入至表示物件內容的 GradeViewer 類別:

    ' Create an ObjectContext instance based on SchoolEntity.
    Private schoolContext As SchoolEntities
    
    // Create an ObjectContext instance based on SchoolEntity.
    private SchoolEntities schoolContext;
    
  4. GradeViewer_Load 事件處理常式中加入下列程式碼。此程式碼會初始化物件內容,並將 ComboBox 控制項的資料來源設為傳回所有不具有 nullEnrollmentDatePerson 型別的查詢。

    ' Initialize schoolContext.
    schoolContext = New SchoolEntities()
    
    ' Define the query to retrieve students.
    Dim studentQuery As ObjectQuery(Of Person) = schoolContext _
        .People.Where("it.EnrollmentDate is not null") _
        .OrderBy("it.LastName")
    
    ' Execute and bind the studentList control to the query.
    studentList.DataSource = studentQuery _
        .Execute(MergeOption.OverwriteChanges)
    studentList.DisplayMember = "LastName"
    
    schoolContext = new SchoolEntities();
    
    // Define the query to retrieve students.
    ObjectQuery<Person> studentQuery = schoolContext.People
        .Where("it.EnrollmentDate is not null")
        .OrderBy("it.LastName");
    
    // Execute and bind the studentList control to the query.
    studentList.DataSource = studentQuery
        .Execute(MergeOption.OverwriteChanges);
    studentList.DisplayMember = "LastName";
    
  5. 回到 GradeViewer 表單的設計檢視,然後按兩下 studentListComboBox 控制項。

    studentList_SelectedIndexChanged 事件處理常式會加入至程式碼後置的檔案。

  6. 將下列程式碼加入至 studentList_SelectedIndexChanged 事件處理常式。此程式碼會執行 GetStudentGradesFunctionImport,並在從下拉式清單選取新的學生時將結果繫結至 DataGridView 控制項。

    ' Get the selected student so we can use the
    ' PersonID in the function import call.
    Dim currentStudent As Person = CType(Me.studentList _
        .SelectedItem(), Person)
    
    ' Set the data source for the gradeGridView
    ' to the results returned by the GetStudentGrades
    ' Function Import.
    gradeGridView.DataSource = schoolContext _
        .GetStudentGrades(currentStudent.PersonID)
    gradeGridView.Columns("Course").Visible = False
    gradeGridView.Columns("StudentID").Visible = False
    gradeGridView.Columns("Person").Visible = False
    gradeGridView.Columns("EnrollmentID").Visible = False
    gradeGridView.AllowUserToAddRows = False
    gradeGridView.AllowUserToDeleteRows = False
    
    // Get the selected student so we can use the
    // PersonID in the function import call.
    Person currentStudent = (Person)this.studentList
        .SelectedItem;
    
    // Set the data source for the gradeGridView
    // to the results returned by the GetStudentGrades
    // Function Import.
    gradeGridView.DataSource = schoolContext
        .GetStudentGrades(currentStudent.PersonID);
    gradeGridView.Columns["Course"].Visible = false;
    gradeGridView.Columns["StudentID"].Visible = false;
    gradeGridView.Columns["Person"].Visible = false;
    gradeGridView.Columns["EnrollmentID"].Visible = false;
    gradeGridView.AllowUserToAddRows = false;
    gradeGridView.AllowUserToDeleteRows = false;
    

按 Ctrl + F5 執行應用程式。現在您就可以按一下 [View Grades],並從 Grade Viewer 表單中的下拉式清單選取學生,藉此檢視學生成績資訊。

列出程式碼

本章節包含 GradeViewer 表單之最終版本的程式碼後置檔案。

Imports System.Data.Objects
Imports System.Data.Objects.DataClasses
Public Class GradeViewer
    ' Create an ObjectContext instance based on SchoolEntity.
    Private schoolContext As SchoolEntities

    Private Sub GradeViewer_Load(ByVal sender As System.Object, _
                ByVal e As System.EventArgs) Handles MyBase.Load
        ' Initialize schoolContext.
        schoolContext = New SchoolEntities()

        ' Define the query to retrieve students.
        Dim studentQuery As ObjectQuery(Of Person) = schoolContext _
            .People.Where("it.EnrollmentDate is not null") _
            .OrderBy("it.LastName")

        ' Execute and bind the studentList control to the query.
        studentList.DataSource = studentQuery _
            .Execute(MergeOption.OverwriteChanges)
        studentList.DisplayMember = "LastName"
    End Sub

    Private Sub studentList_SelectedIndexChanged(ByVal sender As  _
        System.Object, ByVal e As System.EventArgs) Handles _
        studentList.SelectedIndexChanged
        ' Get the selected student so we can use the
        ' PersonID in the function import call.
        Dim currentStudent As Person = CType(Me.studentList _
            .SelectedItem(), Person)

        ' Set the data source for the gradeGridView
        ' to the results returned by the GetStudentGrades
        ' Function Import.
        gradeGridView.DataSource = schoolContext _
            .GetStudentGrades(currentStudent.PersonID)
        gradeGridView.Columns("Course").Visible = False
        gradeGridView.Columns("StudentID").Visible = False
        gradeGridView.Columns("Person").Visible = False
        gradeGridView.Columns("EnrollmentID").Visible = False
        gradeGridView.AllowUserToAddRows = False
        gradeGridView.AllowUserToDeleteRows = False
    End Sub
End Class
using System;
using System.Collections.Generic;
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 CourseManager
{
    public partial class GradeViewer : Form
    {
        // Create an ObjectContext instance based on SchoolEntity.
        private SchoolEntities schoolContext;

        public GradeViewer()
        {
            InitializeComponent();
        }

        private void GradeViewer_Load(object sender, EventArgs e)
        {
            schoolContext = new SchoolEntities();

            // Define the query to retrieve students.
            ObjectQuery<Person> studentQuery = schoolContext.People
                .Where("it.EnrollmentDate is not null")
                .OrderBy("it.LastName");

            // Execute and bind the studentList control to the query.
            studentList.DataSource = studentQuery
                .Execute(MergeOption.OverwriteChanges);
            studentList.DisplayMember = "LastName";
        }

        private void studentList_SelectedIndexChanged(object sender, EventArgs e)
        {
            // Get the selected student so we can use the
            // PersonID in the function import call.
            Person currentStudent = (Person)this.studentList
                .SelectedItem;

            // Set the data source for the gradeGridView
            // to the results returned by the GetStudentGrades
            // Function Import.
            gradeGridView.DataSource = schoolContext
                .GetStudentGrades(currentStudent.PersonID);
            gradeGridView.Columns["Course"].Visible = false;
            gradeGridView.Columns["StudentID"].Visible = false;
            gradeGridView.Columns["Person"].Visible = false;
            gradeGridView.Columns["EnrollmentID"].Visible = false;
            gradeGridView.AllowUserToAddRows = false;
            gradeGridView.AllowUserToDeleteRows = false;
        }
    }
}

後續步驟

您已成功建立一個傳回實體類型集合的 Function Import。如需 Entity Framework 中預存程序之支援的詳細資訊,請參閱Stored Procedure Support (Entity Framework)。如需如何建置使用 Entity Framework 之應用程式的詳細資訊,請參閱Programming Guide (Entity Framework)

另請參閱

其他資源

ADO.NET 實體資料模型設計工具案例
Entity Data Model 工具工作