Share via


逐步解說:建立 Course Manager Web 應用程式

本主題說明如何建立使用 Entity Data Model (EDM) 的基本 ASP.NET 應用程式。CourseManagerWeb 應用程式與適用於 ADO.NET Entity Framework 之快速入門中的 Course Manager Windows Form 應用程式極為類似。

必要條件

若要完成本逐步解說,必須已安裝下列各項:

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

建立方案

此應用程式是以標準 ASP.NET Web 應用程式專案為基礎。

若要在 Visual Studio 中建立 CourseManagerWeb 方案。

  1. 在 Visual Studio 的 [檔案] 功能表上選取 [新增],然後按一下 [專案]。

    隨即會顯示 [新增專案] 對話方塊。

  2. 選取 [專案類型] 窗格中的 [Visual Basic] 或 [Visual C#]。指定 [ASP.NET Web 應用程式] 的 [範本] 類型,然後輸入名稱 CourseManagerWeb

  3. 按一下 [確定]。

  4. 確認方案已經產生,而且它包含 Default.aspx 和 Web.config 檔案。

產生 School Entity Data Model

此應用程式會將 ASP.NET 控制項繫結至 EDM,藉以顯示資料。

若要產生 School EDM

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

  2. 選取 [範本] 窗格中的 [ADO.NET 實體資料模型]。

  3. 輸入 School.edmx 當做模型名稱,然後按一下 [加入]。

    [Entity Data Model 精靈] 的開始頁隨即出現。

  4. 選取 [選擇模型內容] 對話方塊中的 [從資料庫產生],然後按一下 [下一步]。

    [選擇您的資料連接] 對話方塊隨即出現。

  5. 按一下 [新增連接] 按鈕。

    隨即會顯示 [連接屬性] 對話方塊。

  6. 輸入伺服器名稱,並選取驗證方法,然後輸入 School 當做資料庫名稱,再按一下 [確定]。

    [選擇您的資料連接] 對話方塊會更新成資料庫連接設定。

  7. 確定 [將 Web.Config 中的實體連接設定儲存為:] 處於選取狀態,而且值是設為 SchoolEntities。按一下 [下一步]。

    隨即會顯示 [選擇您的資料庫物件] 對話方塊。

  8. 請確定所有資料表都已選取,而且 [模型命名空間] 的值為 SchoolModel,然後按一下 [完成] 完成此精靈。

    此精靈會執行下列各項:

    • 加入 System.Data.EntitySystem.Runtime.SerializationSystem.Security 命名空間的參考。

    • 產生可定義 EDM 的 School.edmx 檔案。

    • 建立原始程式碼檔案,其中包含根據 EDM 所產生的類別。若要檢視原始程式碼檔案,請在 [方案總管] 中展開 Default.aspx 節點。

    • 更新 Web.Config 檔案的連接字串 (Connection String) 區段。

在繼續下一個步驟之前,請在 ADO.NET 實體資料模型設計工具 (預設檢視器) 中開啟 School.edmx 檔案,以便加以檢查。

Note附註

針對 Visual Basic 專案,在 [方案總管] 中可能看不到有些檔案。若要看到所有專案檔案,請按一下 Visual Studio 工作列上的 [專案],然後選取 [顯示所有檔案]。

建立使用者介面 (UI)

此應用程式的 UI 會包含 HTML 和 ASP.NET Web 控制項。

若要建立 CourseManager Web 網頁

  1. 以滑鼠右鍵按一下 CourseManagerWeb 專案中的預設 Web 網頁 (Default.aspx),然後選取 [設計工具檢視]。

    該檔案會在 [Web 網頁設計工具] 中開啟。

  2. 刪除新的 ASP.NET Web 應用程式中自動產生的預設 [div] 區段。

  3. 從 [工具箱] 將 [DropDownList] 控制項拖曳至設計介面,並設定下列屬性:

    • [ID] 為 departmentList

    • [AutoPostBack] 為 True

  4. 展開 [工具箱] 的 [資料],然後將 [EntityDataSource] 控制項拖曳至面板。將它的 [ID] 屬性變更為 departmentDS

  5. 將 [GridView] Web 控制項拖曳至面板,並將它的 [ID] 屬性設為 courseGridView

現已完成 UI。

繫結 DropDownList 控制項

接下來,您會將 DropDownList 控制項繫結至 EntityDataSource 控制項,讓 DropDownList 能顯示科系名稱。

若要繫結 DropDownList 控制項

  1. 按 Ctrl + F5 建置應用程式。必須執行這項動作,才能讓模型中繼資料供 [設定資料來源精靈] 使用,而您將在下一個步驟中使用此精靈。

  2. 在 [Web 網頁設計工具] 視窗中選取 departmentDSEntityDataSource 控制項,然後按一下它的智慧標籤,再選取 [設定資料來源] 命令。

    [設定資料來源精靈] 隨即開啟。

  3. 在 [設定 ObjectContext] 對話方塊內,從 [具名的連接] 下拉式清單中選取 [SchoolEntities]。

  4. 從 [預設容器] 下拉式清單中選取 [SchoolEntities]。

  5. 按一下 [下一步]。

  6. 在 [設定資料選取範圍] 對話方塊中執行下列各項:

    1. 從 [EntitySetName] 下拉式清單中選取 [Department]。

    2. 從 [EntityTypeFilter] 下拉式清單中選取 [(無)]。

    3. 在 [選取] 方塊中選取 [DepartmentID] 和 [Name] 欄位。

    4. 按一下 [完成] 完成設定資料來源。

  7. 回到 Web 網頁的設計檢視。

  8. 選取 departmentListDropDownList 控制項,然後按一下智慧標籤,再按一下 [選擇資料來源]。

    [資料來源組態精靈] 的 [選擇資料來源] 對話方塊隨即開啟。

  9. 在 [選擇資料來源] 對話方塊中進行下列選擇:

    • 針對 [選取資料來源],選取 [departmentDS]。

    • 針對 [選取要顯示在 DropDownList 中的資料欄位],選取 [Name]。

    • 針對 [選取 DropDownList 值的資料欄位],選取 [DepartmentID]。

    Note附註

    如果下拉式清單中沒有可用的值,請按一下 [重新整理結構描述]。

  10. 按一下 [確定]。

該方案將立即建置成功。執行該應用程式時,會將科系名稱填入 DropDownList 控制項。選取科系時,表單將會進行張貼動作,但尚未顯示班別課程表資訊。

繫結 GridView 控制項

接下來,您會加入程式碼,讓 GridView 控制項顯示所選科系所提供的所有課程。為了這麼做,您必須針對表示 School 模型中之實體和關聯的 Common Language Runtime (CLR) 物件建立強型別查詢。

若要繫結 GridView 控制項

  1. 以滑鼠右鍵按一下 [方案總管] 中的 Default.aspx.vb 或 Default.aspx.cs,然後選取 [檢視程式碼]。

  2. 加入下列 using (C#) 或 Imports (Visual Basic) 陳述式 (Statement),以便參考您從 School 資料庫建立的模型,以及實體命名空間 (Namespace)。

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

    ' Create an ObjectContext based on SchoolEntity.
    Private schoolContext As SchoolEntities
    
    // Create an ObjectContext based on SchoolEntity.
    private SchoolEntities schoolContext;
    
  4. 在現有的網頁 Load 事件處理常式內加入下列程式碼,以便初始化 schoolContext 屬性。

     ' Initialize the ObjectContext.
    schoolContext = New SchoolEntities()
    
    // Initialize the data context.
    schoolContext = new SchoolEntities();
    
  5. 回到 Default.aspx Web 網頁的設計檢視。按兩下 departmentListDropDownList 控制項。

    這樣會將 departmentList 控制項的 SelectedIndexChanged 事件處理常式加入至 Default.aspx.vb 或 Default.aspx.cs 檔案。

  6. 將下列程式碼貼至 SelectedIndexChanged 事件處理常式:

    'Get the department ID.
    Dim departmentID As Int32 = CType(departmentList.SelectedValue, Int32)
    
        ' Select course information based on department ID.
        Dim courseInfo = _
            From c In schoolContext.Course _
            Where c.Department.DepartmentID = departmentID _
            Select New With _
            { _
                .CourseID = c.CourseID, _
                .CourseName = c.Title, _
                .CourseCredits = c.Credits _
            }
    
        ' Bind the GridView control to the courseInfo collection.
        courseGridView.DataSource = courseInfo
        courseGridView.DataBind()
    
    // Get the department ID.
    Int32 departmentID = Convert.ToInt32(departmentList.SelectedValue);
    
    // Select course information based on department ID.
    var courseInfo = from c in schoolContext.Course
                    where c.Department.DepartmentID == departmentID
                    select new
                    {
                        CourseID = c.CourseID,
                        CourseTitle = c.Title,
                        CourseCredits = c.Credits
                    };
    
    // Bind the GridView control to the courseInfo collection.
    courseGridView.DataSource = courseInfo;
    courseGridView.DataBind();
    

    這個程式碼會使用 LINQ to Entities 查詢,以根據提供的 DepartmentID 取得課程資訊。此查詢會產生匿名型別的集合,其中包含課程 ID、課程標題和課程學分。然後,此集合會被繫結至 GridView 控制項。

  7. 在 Default.aspx.vb 或 Default.aspx.cs 檔案中將 PreRenderComplete 事件處理常式加入至 _Default 類別。加入下列程式碼,以便在第一次顯示網頁時初始化 GridView 控制項。

    Private Sub Page_PreRenderComplete(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRenderComplete
        ' Force initial GridView update.
        departmentList_SelectedIndexChanged(Me, New EventArgs())
    End Sub
    
    protected void Page_PreRenderComplete(object sender, EventArgs e)
    {
        // Force initial GridView update.
        departmentList_SelectedIndexChanged(this.Page, new EventArgs());
    }
    

該應用程式將立即建置成功而且提供完整的功能。從下拉式清單中選取不同的科系會使表單進行張貼動作,而且使 GridView 控制項更新成對應的課程資訊。

列出程式碼

本章節列出預設 Web 網頁主體之最終版本的程式碼,以及 CourseManagerWeb 方案之最終版本的程式碼後置檔案。

預設 Web 網頁主體

<body>
  <form id="form1" >
    <asp:DropDownList ID="departmentList"  
         AutoPostBack="True" DataSourceID="departmentDS" 
        DataTextField="Name" DataValueField="DepartmentID" 
        onselectedindexchanged="departmentList_SelectedIndexChanged"> 
    </asp:DropDownList>
    
    <asp:EntityDataSource ID="departmentDS"  
       ConnectionString="name=SchoolEntities"
       DefaultContainerName="SchoolEntities" 
       EntitySetName="Department" Select="it.[DepartmentID], 
       it.[Name]">
    </asp:EntityDataSource>

    <asp:GridView ID="courseGridView" >
    </asp:GridView>

    <asp:Button ID="closePage"  Text="Close" 
       onclick="closePage_Click" />
  </form>
</body>

程式碼後置的檔案

Imports System.Data.Objects
Partial Public Class _Default
    Inherits System.Web.UI.Page
    ' Create an ObjectContext based on SchoolEntity.
    Private schoolContext As SchoolEntities

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        ' Initialize the ObjectContext.
        schoolContext = New SchoolEntities()
    End Sub

    Protected Sub departmentList_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles departmentList.SelectedIndexChanged
    'Get the department ID.
    Dim departmentID As Int32 = CType(departmentList.SelectedValue, Int32)

        ' Select course information based on department ID.
        Dim courseInfo = _
            From c In schoolContext.Course _
            Where c.Department.DepartmentID = departmentID _
            Select New With _
            { _
                .CourseID = c.CourseID, _
                .CourseName = c.Title, _
                .CourseCredits = c.Credits _
            }

        ' Bind the GridView control to the courseInfo collection.
        courseGridView.DataSource = courseInfo
        courseGridView.DataBind()
    End Sub
    Private Sub Page_PreRenderComplete(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRenderComplete
        ' Force initial GridView update.
        departmentList_SelectedIndexChanged(Me, New EventArgs())
    End Sub
End Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.Objects;
namespace CourseManagerWeb
{
    public partial class _Default : System.Web.UI.Page
    {
        // Create an ObjectContext based on SchoolEntity.
        private SchoolEntities schoolContext;

        protected void Page_PreRenderComplete(object sender, EventArgs e)
        {
            // Force initial GridView update.
            departmentList_SelectedIndexChanged(this.Page, new EventArgs());
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            // Initialize the data context.
            schoolContext = new SchoolEntities();
        }

        protected void departmentList_SelectedIndexChanged(object sender, EventArgs e)
        {
            // Get the department ID.
            Int32 departmentID = Convert.ToInt32(departmentList.SelectedValue);
            
            // Select course information based on department ID.
            var courseInfo = from c in schoolContext.Course
                            where c.Department.DepartmentID == departmentID
                            select new
                            {
                                CourseID = c.CourseID,
                                CourseTitle = c.Title,
                                CourseCredits = c.Credits
                            };

            // Bind the GridView control to the courseInfo collection.
            courseGridView.DataSource = courseInfo;
            courseGridView.DataBind();
        }
    }
}

後續的步驟

您已成功建立並執行 CourseManagerWeb 應用程式。如需 Entity Framework 的詳細資訊,請參閱 ADO.NET Entity Framework

另請參閱

其他資源

快速入門 (Entity Framework)
範例 (Entity Framework)
物件服務 (Entity Framework)
處理實體資料