다음을 통해 공유


연습: Course Manager 웹 응용 프로그램 만들기

이 항목에서는 EDM(엔터티 데이터 모델)을 사용하는 ASP.NET 응용 프로그램을 만드는 방법에 대해 설명합니다. CourseManagerWeb 응용 프로그램은 ADO.NET Entity Framework에 대한 퀵 스타트의 Course Manager Windows Forms 응용 프로그램과 유사합니다.

필수 구성 요소

이 연습을 수행하려면 다음을 설치해야 합니다.

  • Microsoft Visual Studio 2008 SP1

  • School 샘플 데이터베이스. 이 작은 데이터베이스를 만드는 방법에 대한 자세한 내용은 Creating the School Sample Database를 참조하십시오.

이 연습에서는 독자가 Visual Studio, .NET Framework 및 Visual C# 또는 Visual Basic 프로그래밍에 대한 기본적인 지식을 가지고 있다고 가정합니다.

솔루션 만들기

이 응용 프로그램은 표준 ASP.NET 웹 응용 프로그램 프로젝트를 기반으로 합니다.

Visual Studio에서 CourseManagerWeb 솔루션을 만들려면

  1. Visual Studio의 파일 메뉴에서 새로 만들기를 선택하고 프로젝트를 클릭합니다.

    새 프로젝트 대화 상자가 표시됩니다.

  2. 프로젝트 형식 창에서 Visual Basic 또는 **Visual C#**을 선택합니다. ASP.NET 웹 응용 프로그램템플릿 형식을 지정하고 이름을 CourseManagerWeb으로 입력합니다.

  3. 확인을 클릭합니다.

  4. 솔루션이 생성되었으며 Default.aspx 및 Web.config 파일이 포함되어 있는지 확인합니다.

School 엔터티 데이터 모델 생성

이 응용 프로그램은 ASP.NET 컨트롤을 EDM에 바인딩하여 데이터를 표시합니다.

School EDM을 생성하려면

  1. 솔루션 탐색기에서 CourseManagerWeb 프로젝트를 마우스 오른쪽 단추로 클릭하고 추가를 가리킨 다음 새 항목을 클릭합니다.

  2. 템플릿 창에서 ADO.NET 엔터티 데이터 모델을 선택합니다.

  3. 모델 이름으로 School.edmx를 입력하고 추가를 클릭합니다.

    엔터티 데이터 모델 마법사 시작 페이지가 나타납니다.

  4. Model 콘텐츠 선택 대화 상자에서 데이터베이스에서 생성을 선택한 후 다음을 클릭합니다.

    데이터 연결 선택 대화 상자가 나타납니다.

  5. 새 연결 단추를 클릭합니다.

    연결 속성 대화 상자가 표시됩니다.

  6. 서버 이름을 입력하고, 인증 방법을 선택하고, 데이터베이스 이름으로 School을 입력한 다음 확인을 클릭합니다.

    데이터 연결 선택 대화 상자가 데이터베이스 연결 설정으로 업데이트됩니다.

  7. **다른 이름으로 Web.Config의 entity 연결 설정 저장:**이 선택되어 있고 값이 SchoolEntities로 설정되어 있는지 확인합니다. 다음을 클릭합니다.

    데이터베이스 개체 선택 대화 상자가 표시됩니다.

  8. 모든 테이블이 선택되어 있으며 모델 네임스페이스의 값이 SchoolModel인지 확인한 다음 마침을 클릭하여 마법사를 완료합니다.

    마법사는 다음을 수행합니다.

    • System.Data.Entity, System.Runtime.SerializationSystem.Security 네임스페이스에 대한 참조를 추가합니다.

    • EDM을 정의하는 School.edmx 파일을 생성합니다.

    • EDM을 기반으로 생성된 클래스가 포함된 소스 코드 파일을 만듭니다. 소스 코드 파일을 보려면 솔루션 탐색기에서 Default.aspx 노드를 확장합니다.

    • Web.Config 파일의 연결 문자열 섹션을 업데이트합니다.

다음 단계로 이동하기 전에 ADO.NET 엔터티 데이터 모델 디자이너(기본 뷰어)에서 School.edmx 파일을 열어 검사합니다.

Bb896242.note(ko-kr,VS.100).gif참고:
Visual Basic 프로젝트의 경우 일부 파일이 솔루션 탐색기에 표시되지 않을 수도 있습니다. 모든 프로젝트 파일을 보려면 Visual Studio 작업 표시줄에서 프로젝트를 클릭하고 모든 파일 표시를 선택합니다.

UI(사용자 인터페이스) 만들기

이 응용 프로그램의 UI에는 HTML 및 ASP.NET 웹 컨트롤이 포함됩니다.

CourseManager 웹 페이지를 만들려면

  1. CourseManagerWeb 프로젝트에서 기본 웹 페이지(Default.aspx)를 마우스 오른쪽 단추로 클릭하고 뷰 디자이너를 선택합니다.

    파일이 웹 페이지 디자이너에서 열립니다.

  2. 새 ASP.NET 웹 응용 프로그램에서 자동으로 생성되는 기본 div 섹션을 삭제합니다.

  3. 도구 상자에서 DropDownList 컨트롤을 디자인 화면으로 끌어다 놓고 다음 속성을 설정합니다.

    • IDdepartmentList로 설정

    • AutoPostBackTrue로 설정

  4. 도구 상자의 데이터 섹션을 확장하고 EntityDataSource 컨트롤을 패널로 끌어다 놓습니다. 해당 ID 속성을 departmentDS로 변경합니다.

  5. GridView 웹 컨트롤을 패널로 끌어다 놓고 해당 ID 속성을 courseGridView로 설정합니다.

이제 UI가 완료되었습니다.

다음에는 DropDownList에 부서 이름이 표시되도록 DropDownList 컨트롤을 EntityDataSource 컨트롤에 바인딩합니다.

  1. Ctrl + F5를 눌러 응용 프로그램을 빌드합니다. 다음 단계에서 사용할 모델 메타데이터를 데이터 소스 구성 마법사에서 사용할 수 있도록 하려면 이 작업을 수행해야 합니다.

  2. 웹 페이지 디자이너 창에서 departmentDSEntityDataSource 컨트롤을 선택하고 해당 스마트 태그를 클릭한 다음 데이터 소스 구성 명령을 선택합니다.

    데이터 소스 구성 마법사가 시작됩니다.

  3. ObjectContext 구성 대화 상자의 명명된 연결 드롭다운 목록에서 SchoolEntities를 선택합니다.

  4. 기본 컨테이너 드롭다운 목록에서 SchoolEntities를 선택합니다.

  5. 다음을 클릭합니다.

  6. 데이터 선택 구성 대화 상자에서 다음을 수행합니다.

    1. EntitySetName 드롭다운 목록에서 부서를 선택합니다.

    2. EntityTypeFilter 드롭다운 목록에서 **(없음)**을 선택합니다.

    3. 선택 상자에서 DepartmentID이름 필드를 선택합니다.

    4. 마침을 클릭하여 데이터 소스 구성을 마칩니다.

  7. 웹 페이지의 디자인 뷰로 돌아갑니다.

  8. departmentList DropDownList 컨트롤을 선택하고 스마트 태그를 클릭한 다음 데이터 소스 선택을 클릭합니다.

    데이터 소스 구성 마법사의 데이터 소스 선택 대화 상자가 나타납니다.

  9. 데이터 소스 선택 대화 상자에서 다음을 선택합니다.

    • 데이터 소스 선택에 대해 departmentDS를 선택합니다.

    • DropDownList에 표시할 데이터 필드 선택에 대해 이름을 선택합니다.

    • DropDownList의 값에 대한 데이터 필드 선택에 대해 DepartmentID를 선택합니다.

    Bb896242.note(ko-kr,VS.100).gif참고:
    드롭다운 목록에서 사용할 수 있는 값이 없는 경우 스키마 새로 고침을 클릭합니다.

  10. 확인을 클릭합니다.

이제 솔루션이 성공적으로 빌드됩니다. 응용 프로그램을 실행하면 DropDownList 컨트롤이 부서 이름으로 채워집니다. 부서를 선택하면 폼이 게시되지만 클래스 예약 정보는 표시되지 않습니다.

GridView 컨트롤 바인딩

다음에는 선택한 부서에서 제공되는 모든 과정이 GridView 컨트롤에 표시되도록 코드를 추가합니다. 이렇게 하려면 School 모델의 엔터티와 연결을 나타내는 CLR(공용 언어 런타임) 개체에 대해 강력한 형식의 쿼리를 만듭니다.

GridView 컨트롤을 바인딩하려면

  1. 솔루션 탐색기에서 Default.aspx.vb 또는 Default.aspx.cs를 마우스 오른쪽 단추로 클릭하고 코드 보기를 선택합니다.

  2. School 데이터베이스와 엔터티 네임스페이스에서 만든 모델을 참조하는 다음 using(C#) 또는 Imports(Visual Basic) 문을 추가합니다.

    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 컨트롤을 두 번 클릭합니다.

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

    이 코드에서는 LINQ to Entities 쿼리를 사용하여 제공된 DepartmentID를 기반으로 과정 정보를 가져옵니다. 쿼리는 과정 ID, 과정 제목 및 과정 학점이 포함된 익명 형식의 컬렉션을 생성합니다. 그런 다음 이 컬렉션은 GridView 컨트롤에 바인딩됩니다.

  7. Default.aspx.vb 또는 Default.aspx.cs 파일의 _Default 클래스에 PreRenderComplete 이벤트 처리기를 추가합니다. 페이지가 처음 표시될 때 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.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();
        }
    }
}

다음 단계

CourseManagerWeb 응용 프로그램을 성공적으로 만들어 실행했습니다. Entity Framework에 대한 자세한 내용은 ADO.NET Entity Framework를 참조하십시오.

참고 항목

기타 리소스

Quickstart
Samples (Entity Framework)
Object Services (Entity Framework)
Querying an Entity Data Model