Запросы к сущностям и ассоциациям (краткое руководство по платформе Entity Framework)

В этой задаче создаются строго типизированные запросы к объектам среды CLR, которые представляют сущности и ассоциации в модели School, а элементы управления отображением привязываются к коллекциям объектов, возвращаемым этими запросами.

Запрос по отделам в базе данных School

  1. В начале файла с кодом для формы CourseViewer добавьте директиву using (C#) или Imports (Visual Basic), чтобы сослаться на модель, созданную из базы данных School, и пространство имен сущностей.

    Imports System.Data.Objects
    Imports System.Data.Objects.DataClasses
    
    using System.Data.Objects;
    using System.Data.Objects.DataClasses;
    
  2. В начале определения разделяемого класса для формы CourseViewer добавьте следующий код, создающий экземпляр 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) = _
        From d In schoolContext.Departments.Include("Courses") _
        Order By d.Name _
        Select d
    Try
        ' Bind the ComboBox control to the query.
        ' To prevent the query from being executed multiple times during binding, 
        ' it is recommended to bind controls to the result of the Execute method. 
        Me.departmentList.DisplayMember = "Name"
        Me.departmentList.DataSource = CType(departmentQuery, ObjectQuery).Execute(MergeOption.AppendOnly)
    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 course objects, ordered by name.
    var departmentQuery = from d in schoolContext.Departments.Include("Courses")
                          orderby d.Name
                          select d;
    try
    {
        // Bind the ComboBox control to the query, 
        // which is executed during data binding.
        // To prevent the query from being executed multiple times during binding, 
        // it is recommended to bind controls to the result of the Execute method. 
        this.departmentList.DisplayMember = "Name";
        this.departmentList.DataSource = ((ObjectQuery)departmentQuery).Execute(MergeOption.AppendOnly);
    }
    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.Courses
    
        ' Hide the columns that are bound to the navigation properties on Course.
        courseGridView.Columns("Department").Visible = False
        courseGridView.Columns("StudentGrades").Visible = False
        courseGridView.Columns("OnlineCourse").Visible = False
        courseGridView.Columns("OnsiteCourse").Visible = False
        courseGridView.Columns("People").Visible = False
        courseGridView.Columns("DepartmentId").Visible = False
    
        courseGridView.AllowUserToDeleteRows = False
    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.Courses;
    
            // Hide the columns that are bound to the navigation properties on Course.
            courseGridView.Columns["Department"].Visible = false;
            courseGridView.Columns["StudentGrades"].Visible = false;
            courseGridView.Columns["OnlineCourse"].Visible = false;
            courseGridView.Columns["OnsiteCourse"].Visible = false;
            courseGridView.Columns["People"].Visible = false;
            courseGridView.Columns["DepartmentId"].Visible = false;
    
            courseGridView.AllowUserToDeleteRows = false;
    courseGridView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    

Следующие шаги

Были успешно созданы запросы, возвращающие объекты Department и Course и связывающие эти объекты с элементами управления. После этого необходимо сохранить изменения, выполненные для объектов Course в сетке данных, в базе данных: Вставка и обновление данных (краткое руководство по платформе Entity Framework).

См. также

Основные понятия

Выполнение запроса к концептуальной модели (платформа Entity Framework)
Работа с данными сущностей

Другие ресурсы

Образцы (платформа Entity Framework)