Esecuzione di query su entità e associazioni (guida rapida di Entity Framework)

In questa attività verranno create query fortemente tipizzate sugli oggetti CLR che rappresentano entità e associazioni nel modello School e verranno associati controlli di visualizzazione alle raccolte di oggetti restituiti da queste query.

Per eseguire una query sui dipartimenti nel database School

  1. All'inizio del file di codice per il form CourseViewer aggiungere le seguenti istruzioni using (C#) o Imports (Visual Basic) per fare riferimento al modello creato dal database School e allo spazio dei nomi dell'entità.

    Imports System.Data.Objects
    Imports System.Data.Objects.DataClasses
    
    using System.Data.Objects;
    using System.Data.Objects.DataClasses;
    
  2. All'inizio della definizione di classe parziale per il form CourseViewer aggiungere il codice seguente che consente di creare un'istanza di ObjectContext.

    ' Create an ObjectContext instance based on SchoolEntity.
    Private schoolContext As SchoolEntities
    
    //Create an ObjectContext instance based on SchoolEntity
    private SchoolEntities schoolContext;
    
  3. Nella finestra di progettazione dei form di CourseViewer fare doppio clic sul form CourseViewer.

    Verrà visualizzata la pagina di codice per il form e verrà creato il metodo del gestore eventi courseViewer _Load.

  4. Nel metodo del gestore eventi courseViewer _Load copiare e incollare il codice seguente che consente di definire l'oggetto DataGridView, di eseguire una query che restituisce una raccolta di reparti (ordinato in base a Name) e di associare la raccolta di oggetti Department al controllo 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);
    }
    

Per visualizzare i corsi per il dipartimento selezionato

  1. Nella finestra di progettazione dei form di CourseViewer fare doppio clic sul controllo departmentList.

    Verrà creato il metodo del gestore eventi departmentList_SelectedIndexChanged.

  2. Incollare il codice seguente che consente di caricare i corsi correlati al dipartimento selezionato.

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

Passaggi successivi

Sono state create correttamente query che restituiscono oggetti Department e Course e tali oggetti sono stati associati ai controlli. Le modifiche apportate agli oggetti Course nella griglia dei dati verranno quindi di nuovo salvate nel database: Inserimento e aggiornamento di dati (guida rapida di Entity Framework).

Vedere anche

Concetti

Esecuzione di query su un modello concettuale (Entity Framework)
Utilizzo di dati delle entità

Altre risorse

Esempi (Entity Framework)