Abfragen von Entitäten und Zuordnungen (Entity Framework-Schnellstart)

In dieser Aufgabe erstellen Sie stark typisierte Abfragen für CLR-Objekte, die Entitäten und Zuordnungen im Modell "School" darstellen. Des Weiteren binden Sie Anzeigesteuerelemente an die von diesen Abfragen zurückgegebenen Objektauflistungen.

So fragen Sie die Abteilungen in der Datenbank "School" ab

  1. Fügen Sie am Anfang der Codedatei für das CourseViewer-Formular folgende using-Anweisung(C#) oder Imports-Anweisung (Visual Basic) hinzu, um auf das aus der Datenbank "School" erstellte Modell und den Entity Namespace zu verweisen.

    Imports System.Data.Objects
    Imports System.Data.Objects.DataClasses
    
    using System.Data.Objects;
    using System.Data.Objects.DataClasses;
    
  2. Fügen Sie zu Beginn der partiellen Klassendefinition für das CourseViewer-Formular den folgenden Code hinzu, mit dem eine ObjectContext-Instanz erstellt wird.

    ' Create an ObjectContext instance based on SchoolEntity.
    Private schoolContext As SchoolEntities
    
    //Create an ObjectContext instance based on SchoolEntity
    private SchoolEntities schoolContext;
    
  3. Doppelklicken Sie im CourseViewer-Formular-Designer auf das CourseViewer-Formular.

    Daraufhin wird die Codepage für das Formular geöffnet und die courseViewer _Load-Ereignishandlermethode erstellt.

  4. Kopieren Sie folgenden Code, und fügen Sie ihn in der courseViewer _Load-Ereignishandlermethode ein. Mit diesem Code wird die DataGridView definiert, eine Abfrage ausgeführt, die eine Auflistung von Abteilungen (geordnet nach Name) zurückgibt, sowie die Auflistung von Department-Objekten an das departmentList-Steuerelement gebunden.

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

So zeigen Sie Kurse für die ausgewählte Abteilung an

  1. Doppelklicken Sie im CourseViewer-Formulardesigner auf das departmentList-Steuerelement.

    Durch diese Aktion wird die departmentList_SelectedIndexChanged-Ereignishandlermethode erstellt.

  2. Fügen Sie den folgenden Code ein, mit dem die zur ausgewählten Abteilung gehörenden Kurse geladen werden.

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

Nächste Schritte

Sie haben erfolgreich Abfragen erstellt, mit denen Department-Objekte und Course-Objekts zurückgegeben werden und diese Objekte an Steuerelemente gebunden. Im nächsten Schritt werden Sie im Datenraster vorgenommene Änderungen an Course-Objekten in der Datenbank speichern: Einfügen und Aktualisieren von Daten (Entity Framework-Schnellstart).

Siehe auch

Konzepte

Abfragen eines konzeptionellen Modells (Entity Framework)
Arbeiten mit Entitätsdaten

Weitere Ressourcen

Beispiele (Entity Framework)