演练:创建 Course Manager Web 应用程序

本主题介绍如何创建使用实体数据模型 (EDM) 的基本 ASP.NET 应用程序。该应用程序 CourseManagerWeb 与 ADO.NET 实体框架的快速入门中的 Course Manager Windows 窗体应用程序十分相像。

系统必备

为了完成此演练,必须已安装以下组件:

此演练假定您对于 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 实体数据模型

此应用程序通过将 ASP.NET 控件绑定到 EDM 来显示数据。

生成 School EDM

  1. 在**“解决方案资源管理器”中右键单击 CourseManagerWeb 项目,指向“添加”,然后单击“添加新项”**。

  2. 在**“模板”窗格中,选择“ADO.NET 实体数据模型”**。

  3. 为模型名称键入 School.edmx,然后单击**“添加”**。

    此时出现“实体数据模型向导”的开始页。

  4. 在**“选择模型内容”对话框中,选择“从数据库生成”,然后单击“下一步”**。

    此时出现**“选择您的数据连接”**对话框。

  5. 单击**“新建连接”**按钮。

    将显示**“连接属性”**对话框。

  6. 输入服务器名称,选择身份验证方法,为数据库名称键入 School,然后单击**“确定”**。

    **“选择您的数据连接”**对话框将以数据库连接设置更新。

  7. 确保**“将 Web.Config 中的实体连接设置另存为:”已选中,并且其值设置为 SchoolEntities。单击“下一步”**。

    将显示**“选择数据库对象”**对话框。

  8. 确保选中所有表且**“模型命名空间”的值为 SchoolModel,然后单击“完成”**以完成此向导。

    向导将执行下列操作:

    • 添加对 System.Data.EntitySystem.Runtime.SerializationSystem.Security 命名空间的引用。

    • 生成用于定义 EDM 的 School.edmx 文件。

    • 创建一个源代码文件,其中包含基于该 EDM 生成的类。若要查看源代码文件,请在**“解决方案资源管理器”**中展开 Default.aspx 节点。

    • 更新 Web.Config 文件的连接字符串部分。

继续下一步骤之前,在 ADO.NET 实体数据模型设计器(默认查看器)中打开 School.edmx 文件进行检查。

Note注意

对于 Visual Basic 项目,有些文件在“解决方案资源管理器”中可能不可见。若要查看所有项目文件,请在 Visual Studio 任务栏中单击“项目”并选择“显示所有文件”

创建用户界面 (UI)

此应用程序的 UI 包含 HTML 和 ASP.NET Web 控件。

创建 CourseManager 网页

  1. 在 CourseManagerWeb 项目中,右键单击默认网页 (Default.aspx) 并选择**“视图设计器”**。

    将在网页设计器中打开该文件。

  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. 在**“网页设计器”窗口中,选择 departmentDSEntityDataSource 控件,单击其智能标记并选择“配置数据源”**命令。

    这将启动数据源配置向导。

  3. 在**“配置 ObjectContext”对话框中,从“命名连接”下拉列表中选择“SchoolEntities”**。

  4. 从**“默认容器”下拉列表中选择“SchoolEntities”**。

  5. 单击**“下一步”**。

  6. 在**“配置数据选择”**对话框中,执行以下操作:

    1. 从**“EntitySetName”下拉列表中选择“Department”**。

    2. 从**“EntityTypeFilter”下拉列表中选择“(无)”**。

    3. 选中**“选择”框中的“DepartmentID”“Name”**字段。

    4. 单击**“完成”**完成数据源配置。

  7. 返回网页的设计视图。

  8. 选择 departmentListDropDownList 控件,单击智能标记,然后单击**“选择数据源”**。

    此时出现数据源配置向导的**“选择数据源”**对话框。

  9. 在**“选择数据源”**对话框中进行以下选择:

    • 对于**“选择数据源”,选择“departmentDS”**。

    • 对于**“选择要在 DropDownList 中显示的数据字段”,选择“Name”**。

    • 对于**“为 DropDownList 的值选择数据字段”,选择“DepartmentID”**。

    Note注意

    如果下拉列表中没有可用的值,则单击“刷新架构”

  10. 单击**“确定”**。

至此将成功生成解决方案。应用程序在运行时将使用部门名称填充 DropDownList 控件。当选择一个部门时,将提交窗体,但还不会显示类计划信息。

绑定 GridView 控件

下一步,添加代码使 GridView 控件显示选中的部门提供的所有课程。为此,要针对表示 School 模型中的实体和关联的公共语言运行库 (CLR) 对象创建强类型查询。

绑定 GridView 控件

  1. 在**“解决方案资源管理器”中,右键单击 Default.aspx.vb 或 Default.aspx.cs 并选择“查看代码”**。

  2. 添加以下 using (C#) 或 Imports (Visual Basic) 语句,以引用基于 School 数据库和实体命名空间创建的模型。

    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. 在现有的页加载事件处理程序中,添加以下代码以初始化 schoolContext 属性。

     ' Initialize the ObjectContext.
    schoolContext = New SchoolEntities()
    
    // Initialize the data context.
    schoolContext = new SchoolEntities();
    
  5. 返回 Default.aspx 网页的设计视图。双击 departmentListDropDownList 控件。

    这将向 Default.aspx.vb 或 Default.aspx.cs 文件添加 departmentList 控件的 SelectedIndexChanged 事件处理程序。

  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. PreRenderComplete 事件处理程序添加到 Default.aspx.vb 或 Default.aspx.cs 文件中的 _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 控件。

代码清单

本节列出默认网页的正文和 CourseManagerWeb 解决方案的代码隐藏文件的代码的最终版本。

默认网页的正文

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

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

    <asp:Button ID="closePage" runat="server" 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 应用程序。有关实体框架的更多信息,请参见 ADO.NET 实体框架

另请参见

其他资源

快速入门(实体框架)
示例(实体框架)
对象服务(实体框架)
使用实体数据