엔터티 및 연결 쿼리(Entity Framework 퀵 스타트)

이 작업에서는 School 모델의 엔터티와 연결을 나타내는 CLR 개체에 대한 강력한 형식의 쿼리를 만든 다음 쿼리에서 반환된 개체 컬렉션에 표시 컨트롤을 바인딩합니다.

School 데이터베이스의 학과를 쿼리하려면

  1. CourseViewer 폼의 코드 파일의 시작 부분에 School 데이터베이스에서 만든 모델과 엔터티 네임스페이스를 참조하는 다음 using(C#) 또는 Imports(Visual Basic) 문을 추가합니다.

    Imports System.Data.Objects
    Imports System.Data.Objects.DataClasses
    
    using System.Data.Objects;
    using System.Data.Objects.DataClasses;
    
  2. CourseViewer 폼의 partial 클래스 정의 맨 위에 ObjectContext 인스턴스를 만드는 다음 코드를 추가합니다.

    ' Create an ObjectContext instance based on SchoolEntity.
    Private schoolContext As SchoolEntities
    
    // Create an ObjectContext instance based on SchoolEntity.
    private SchoolEntities schoolContext;
    
  3. CourseViewer 폼 디자이너에서 CourseViewer 폼을 두 번 클릭합니다.

    그러면 폼에 대한 코드 페이지가 열리고 courseViewer _Load 이벤트 처리기 메서드가 만들어집니다.

  4. courseViewer _Load 이벤트 처리기 메서드에서 DataGridView를 정의하고, 학과 컬렉션(Name을 기준으로 정렬됨)을 반환하는 쿼리를 실행하고, Department 개체 컬렉션을 departmentList 컨트롤에 바인딩하는 다음 코드를 복사하여 붙여 넣습니다.

    ' Initialize the ObjectContext.
    schoolContext = New SchoolEntities()
    
    ' Define a query that returns all Department objects and related
    ' Course objects, ordered by name.
    Dim departmentQuery As ObjectQuery(Of Department) = _
        schoolContext.Department.Include("Course").OrderBy("it.Name")
    
    Try
        ' Bind the ComboBox control to the query, which is 
        ' executed during data binding.
        Me.departmentList.DataSource = departmentQuery
        Me.departmentList.DisplayMember = "Name"
    Catch ex As Exception
        MessageBox.Show(ex.Message)
    End Try
    
    // Initialize the ObjectContext.
    schoolContext = new SchoolEntities();
    
    // Define a query that returns all Department objects and related
    // Course objects, ordered by name.
    ObjectQuery<Department> departmentQuery =
        schoolContext.Department.Include("Course").OrderBy("it.Name");
    
    try
    {
        // Bind the ComboBox control to the query, which is
        // executed during data binding.
        this.departmentList.DataSource = departmentQuery;
        this.departmentList.DisplayMember = "Name";
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
    

선택한 학과의 강의를 표시하려면

  1. CourseViewer 폼 디자이너에서 departmentList 컨트롤을 두 번 클릭합니다.

    그러면 departmentList_SelectedIndexChanged 이벤트 처리기 메서드가 생성됩니다.

  2. 선택한 학과와 관련된 강의를 로드하는 다음 코드를 붙여 넣습니다.

    Try
        ' Get the object for the selected department.
        Dim department As Department = _
            CType(Me.departmentList.SelectedItem, Department)
    
        ' Bind the grid view to the collection of Course objects 
        ' that are related to the selected Department object.
        courseGridView.DataSource = department.Course
        courseGridView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells)
    Catch ex As Exception
        MessageBox.Show(ex.Message)
    End Try
    
    try
    {
        // Get the object for the selected department.
        Department department = 
            (Department)this.departmentList.SelectedItem;
    
        // Bind the grid view to the collection of Course objects 
        // that are related to the selected Department object.
        courseGridView.DataSource = department.Course;
    
        courseGridView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
    

다음 단계

DepartmentCourse 개체를 반환하는 쿼리를 만들어 해당 개체를 컨트롤에 바인딩하는 작업을 성공적으로 완료했습니다. 다음으로는 데이터 표에 있는 Course 개체의 변경 내용을 데이터베이스에 다시 저장합니다. 다음 항목을 참조하십시오. 데이터 삽입 및 업데이트(Entity Framework 퀵 스타트).

참고 항목

개념

엔터티 데이터 사용

기타 리소스

샘플(Entity Framework)
개체 서비스(Entity Framework)