다음을 통해 공유


연습: 저장 프로시저로 엔터티 형식 검색

이 항목에서는 저장 프로시저를 사용하여 엔터티 형식의 컬렉션을 검색하는 방법을 보여 줍니다. 이 연습에서는 ADO.NET 엔터티 데이터 모델 디자이너(Entity Designer)를 사용하여 저장 프로시저를 가져오고 엔터티 형식의 컬렉션을 반환하는 Function Import를 만듭니다.

EDM(엔터티 데이터 모델)에 저장 프로시저를 포함하면 사용하는 응용 프로그램 코드에서 저장 프로시저를 호출할 수 있습니다. 개념적 모델에 저장 프로시저가 추가되면 이를 Function Import라고 합니다. Function Import는 단순 형식이나 엔터티 형식의 컬렉션을 반환하거나 아무 값도 반환하지 않을 수 있습니다.

Note참고

Function Import에서 EntityType을 반환하려면 해당 저장 프로시저에서 반환된 열이 반환된 EntityType의 속성과 정확하게 일치해야 합니다.

엔터티 데이터 모델 마법사에서 데이터베이스를 기반으로 생성된 EDM은 데이터베이스의 각 저장 프로시저에 대한 저장소 모델에서 항목을 만듭니다. Function Import를 만들면 해당 항목이 개념적 모델에 추가됩니다. Function Import를 만드는 방법에 대한 자세한 내용은 방법: 저장 프로시저 가져오기를 참조하십시오.

필수 구성 요소

이 연습을 수행하려면 CourseManager 응용 프로그램을 빌드해야 합니다. 자세한 내용과 지침은 Entity Framework 퀵 스타트를 참조하십시오. 이 응용 프로그램을 빌드한 후 GetStudentGrades 저장 프로시저를 기반으로 Function Import를 만들어 해당 EDM을 수정합니다.

Note참고

이 설명서에 있는 대부분의 연습 항목에서는 CourseManager 응용 프로그램을 시작 지점으로 사용하므로 원래 CourseManager 코드를 편집하지 않고 연습용으로 CourseManager 응용 프로그램을 복사하여 사용하는 것이 좋습니다.

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

Function Import 만들기

이 절차에서는 CourseManager EDM의 저장소 모델에 포함된 GetStudentGrades 저장 프로시저를 기반으로 Function Import를 만듭니다.

Function Import를 만들려면

  1. Visual Studio에서 CourseManager 솔루션을 엽니다.

  2. 솔루션 탐색기에서 School.edmx 파일을 두 번 클릭합니다.

    School.edmx 파일이 ADO.NET 엔터티 데이터 모델 디자이너(Entity Designer)에서 열리고 모델 브라우저 창이 열립니다.

  3. 모델 브라우저 창에서 EntityContainer: SchoolEntities 노드를 확장합니다.

    Entity Sets, Association SetsFunction Imports 폴더가 트리 뷰에 표시됩니다.

  4. Function Imports를 마우스 오른쪽 단추로 클릭하고 Function Import 만들기를 선택합니다.

    New Function Import 대화 상자가 열립니다.

  5. 저장 프로시저 이름 드롭다운 목록에서 GetStudentGrades를 선택합니다.

  6. Function Import 이름 텍스트 상자에 GetStudentGrades를 입력합니다.

  7. 반환 형식 드롭다운 목록에서 CourseGrade를 선택합니다.

    Note참고

    GetStudentGrades 저장 프로시저(EnrollementIDGrade)에서 반환된 열이 CourseGrade 엔터티 형식의 스칼라 속성과 정확하게 일치하기 때문에 반환 형식을 CourseGrade로 설정할 수 있습니다.

  8. 확인을 클릭합니다.

    GetStudentGradesFunction Import가 EDM에 추가됩니다.

사용자 인터페이스 생성

이 절차에서는 선택한 학생의 점수를 볼 수 있도록 CourseManager 응용 프로그램의 사용자 인터페이스에 추가합니다.

사용자 인터페이스를 생성하려면

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

    새 항목 추가 대화 상자가 나타납니다.

  2. Windows Form을 선택하고 폼의 이름을 GradeViewer.vb 또는 GradeViewer.cs로 설정한 다음 추가를 클릭합니다.

    새 폼이 프로젝트에 추가되고 폼 디자이너에서 열립니다. 폼의 이름은 GradeViewer로 설정되고 텍스트는 GradeViewer로 설정됩니다.

  3. 도구 상자에서 ComboBox 컨트롤을 폼으로 끌어다 놓고 속성 창에서 해당 이름studentList로 설정합니다.

  4. 도구 상자에서 DataGridView 컨트롤을 폼으로 끌어다 놓고 속성 창에서 해당 이름gradeGridView로 설정합니다.

  5. 솔루션 탐색기에서 CourseViewer.vb 또는 CourseViewer.cs 파일을 두 번 클릭합니다.

    파일이 폼 디자이너에서 열립니다.

  6. Button 컨트롤을 폼으로 끌어다 놓습니다. 해당 이름viewGrades로 설정하고 텍스트ViewGrades로 설정합니다.

  7. viewGradesButton 컨트롤을 두 번 클릭합니다.

    viewGrades_Click 이벤트 처리기가 코드 숨김 파일에 추가됩니다.

  8. viewGrades_Click 이벤트 처리기에 다음 코드를 추가합니다.

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

이제 사용자 인터페이스가 완료되었습니다.

저장 프로시저로 엔터티 형식 검색

이 절차에서는 앞에서 GetStudentGrades 저장 프로시저를 기반으로 만든 Function Import를 실행하는 코드를 추가합니다. 코드는 반환된 EntityType 컬렉션을 DataGridView 컨트롤에 바인딩합니다. 개체를 컨트롤에 바인딩하는 방법에 대한 자세한 내용은 컨트롤에 개체 바인딩(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 컨트롤의 데이터 소스를 nullEnrollmentDate가 없는 모든 Person 형식을 반환하는 쿼리로 설정합니다.

    ' Initialize schoolContext.
    schoolContext = New SchoolEntities()
    
    ' Define the query to retrieve students.
    Dim studentQuery As ObjectQuery(Of Person) = schoolContext _
        .Person.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.Person
        .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)
    
    // 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);
    

응용 프로그램을 실행하려면 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 _
            .Person.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)
    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.Person
                .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);
        }
    }
}

다음 단계

엔터티 형식의 컬렉션을 검색하는 Function Import가 성공적으로 만들어졌습니다. Entity Framework의 저장 프로시저 지원에 대한 자세한 내용은 저장 프로시저 지원(Entity Framework)을 참조하십시오. Entity Framework를 사용하는 응용 프로그램을 빌드하는 방법에 대한 자세한 내용은 프로그래밍 가이드(Entity Framework)를 참조하십시오.

참고 항목

기타 리소스

ADO.NET 엔터티 데이터 모델 디자이너 시나리오
엔터티 데이터 모델 도구 작업