Walkthrough: Creating the Course Manager Web Application (Entity Data Model Tools)

This topic describes how to create a basic ASP.NET application that uses the Entity Framework. The application, CourseManagerWeb, closely resembles the Course Manager Windows Forms application in the Quickstart for the ADO.NET Entity Framework.

Prerequisites

To complete this walkthrough, you must have the following installed:

This walkthrough assumes that you have basic competency with Visual Studio, the .NET Framework, and programming in either Visual C# or Visual Basic.

Creating the Solution

This application is based on a standard ASP.NET Web Application project.

To create the CourseManagerWeb solution in Visual Studio

  1. From the File menu in Visual Studio, select New, and then click Project.

    The New Project dialog box is displayed.

  2. In the Project Type pane, select either Visual Basic or Visual C#. Specify a Template type of ASP.NET Web Application, and type the name CourseManagerWeb.

  3. Click OK.

  4. Confirm that the solution has been generated and that it contains the Default.aspx and Web.config files.

Generating the School .edmx File

This application displays data by binding ASP.NET controls to an Entity Framework conceptual model.

To generate the School .edmx file

  1. Right-click the CourseManagerWeb project in the Solution Explorer, point to Add, and then click New Item.

  2. Select ADO.NET Entity Data Model in the Templates pane.

  3. Type School.edmx for the model name and then click Add.

    The opening page of the Entity Data Model Wizard appears.

  4. In the Choose Model Contents dialog box, select Generate from database and then click Next.

    The Choose Your Data Connection dialog box appears.

  5. Click the New Connection button.

    The Connection Properties dialog box is displayed.

  6. Enter your server name, select the authentication method, type School for the database name, and then click OK.

    The Choose Your Data Connections dialog box is updated with the database connection settings.

  7. Ensure that Save entity connection settings in Web.Config as: is checked and the value is set to SchoolEntities. Click Next.

    The Choose Your Database Objects dialog box is displayed.

  8. Ensure that all tables are selected and that the value of Model namespace is SchoolModel, and then click Finish to complete the wizard.

    The wizard does the following:

    • Adds references to the System.Data.Entity, System.Runtime.Serialization, and System.Security namespaces.

    • Generates School.edmx, the file that defines the conceptual model, the storage model, and the mapping between the two.

    • Creates a source code file that contains the classes that were generated based on the conceptual model. To view the source code file, expand the Default.aspx node in the Solution Explorer.

    • Updates the connection string section of the Web.Config file.

Before going on to the next step, examine the School.edmx file by opening it in the ADO.NET Entity Data Model Designer (the default viewer).

NoteNote

For Visual Basic projects, some files might not be visible in the Solution Explorer. To see all the project files, click Project in the Visual Studio task bar and select Show All Files.

Creating the User Interface (UI)

The UI for this application contains HTML and ASP.NET Web controls.

To create the CourseManager Web page

  1. In the CourseManagerWeb project, right-click the default Web page (Default.aspx) and select View Designer.

    The file opens in the Web Page Designer.

  2. Delete the default div section that is automatically generated in new ASP.NET Web applications.

  3. From the Toolbox, drag a DropDownList control to the design surface and set the following properties:

    • ID to departmentList

    • AutoPostBack to True

  4. Expand the Data section of the Toolbox and drag an EntityDataSource control to the panel. Change its ID property to departmentDS.

  5. Drag a GridView Web control to the panel and set its ID property to courseGridView.

The UI is now complete.

Binding the DropDownList Control

Next, you bind the DropDownList control to the EntityDataSource control so that the DropDownList will display department names.

To bind the DropDownList control

  1. Press Ctrl + F5 to build the application. This is required to make the model metadata available to the Configure Data Source Wizard, which you will use in the next step.

  2. In the Web Page Designer window, select the departmentDS EntityDataSource control, click its smart tag, and select the Configure Data Source command.

    The Configure Data Source Wizard starts.

  3. In the Configure ObjectContext dialog box, select SchoolEntities from the Named Connection drop-down list.

  4. Select SchoolEntities from the Default Container drop-down list.

  5. Click Next.

  6. In the Configure Data Selection dialog box, do the following:

    1. Select Departments from the EntitySetName drop-down list.

    2. Select (None) from the EntityTypeFilter drop-down list.

    3. Check the DepartmentID and Name fields in the Select box.

    4. Click Finish to finish configuring the data source.

  7. Return to the Design View of the Web page.

  8. Select the departmentList DropDownList control, click on the smart tag, and then click Choose Data Source.

    The Choose a Data Source dialog box of the Data Source Configuration Wizard appears.

  9. In the Choose a Data Source dialog box, make the following selections:

    • For Select Data Source, select departmentDS.

    • For Select a data field to display in the DropDownList, select Name.

    • For Select a data field for the value of the DropDownList, select DepartmentID.

    NoteNote

    If no values are available in the drop-down lists, click Refresh Schema.

  10. Click OK.

The solution will now build successfully. When the application is run, the DropDownList control is populated with the names of departments. When you select a department, the form will post, but class schedule information will not yet be displayed.

Binding the GridView Control

Next, add code so that the GridView control displays all courses offered in the selected department. To do this, you create strongly-typed queries against the common language runtime (CLR) objects that represent entities and associations in the School model.

To bind the GridView control

  1. In the Solution Explorer, right-click Default.aspx.vb or Default.aspx.cs and select View Code.

  2. Add the following using (C#) or Imports (Visual Basic) statements to reference the model that you created from the School database and the entity namespace.

    Imports System.Data.Objects
    
    using System.Data.Objects;
    
  3. Add a property to the _Default class that represents the object context.

    ' Create an ObjectContext based on SchoolEntity.
    Private schoolContext As SchoolEntities
    
    // Create an ObjectContext based on SchoolEntity.
    private SchoolEntities schoolContext;
    
  4. Inside the existing page load event handler, add the following code to initialize the schoolContext property.

    ' Initialize the ObjectContext.
    schoolContext = New SchoolEntities()
    
    // Initialize the data context.
    schoolContext = new SchoolEntities();
    
  5. Return to the Design View of the Default.aspx Web page. Double-click the departmentList DropDownList control.

    This adds a SelectedIndexChanged event handler for the departmentList control to the Default.aspx.vb or Default.aspx.cs file.

  6. Paste the following code into the SelectedIndexChanged event handler:

    '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.Courses _
        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.Courses
                     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();
    

    This code uses a LINQ to Entities query to get the course information based on the provided DepartmentID. The query generates a collection of anonymous types that contains the course ID, course title, and course credits. This collection is then bound to the GridView control.

  7. Add a PreRenderComplete event handler to the _Default class in the Default.aspx.vb or Default.aspx.cs file. Add the following code to initialize the GridView control when the page is first displayed.

    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());
    }
    

The application will now build successfully and is fully functional. Selecting a different department form the drop-down list causes the form to be posted and the GridView control to be updated with corresponding course information.

Code Listing

This section lists the final versions of the code for the body of the default Web page and for the code-behind file of the CourseManagerWeb solution.

Body of Default Web Page

<body>
    <form id="form1" runat="server">
    <asp:DropDownList ID="departmentList" runat="server" 
                      AutoPostBack="True" DataSourceID="departmentDS" 
                      DataTextField="Name" DataValueField="DepartmentID" 
                      Height="19px" Width="161px">
    </asp:DropDownList>
    <asp:EntityDataSource ID="departmentDS" runat="server" 
        ConnectionString="name=SchoolEntities" 
        DefaultContainerName="SchoolEntities" 
        EnableFlattening="False" EntitySetName="Departments" 
        Select="it.[DepartmentID], it.[Name]">
    </asp:EntityDataSource>
    <asp:GridView ID="courseGridView" runat="server">
    </asp:GridView>
    </form>
</body>

Code-Behind File

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.Courses _
            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.Courses
                             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();
        }
    }
}

Next Steps

You have successfully created and run the CourseManagerWeb application. For more information about the Entity Framework, see ADO.NET Entity Framework.

See Also

Other Resources

Quickstart (Entity Framework)
Samples (Entity Framework)
Working with Entity Data