Compartir a través de


Consultar entidades y asociaciones (Tutorial rápido de Entity Framework)

En esta tarea se crearán consultas fuertemente tipadas en los objetos CLR que representan a las entidades y asociaciones del modelo School, y se enlazarán controles de presentación a las colecciones de objetos que devuelvan estas consultas.

Para consultar los departamentos de la base de datos School

  1. Al principio del archivo de código del formulario CourseViewer, agregue las instrucciones siguientes using (C#) o Imports (Visual Basic) para hacer referencia al modelo creado a partir de la base de datos School y del espacio de nombres de entidad.

    Imports System.Data.Objects
    Imports System.Data.Objects.DataClasses
    
    using System.Data.Objects;
    using System.Data.Objects.DataClasses;
    
  2. Al principio de la definición de clase parcial del formulario CourseViewer, agregue el código siguiente que crea una instancia de ObjectContext.

    ' Create an ObjectContext instance based on SchoolEntity.
    Private schoolContext As SchoolEntities
    
    //Create an ObjectContext instance based on SchoolEntity
    private SchoolEntities schoolContext;
    
  3. En el diseñador de formularios de CourseViewer, haga doble clic en el formulario CourseViewer.

    De esta forma se abre la página de código del formulario y se crea el método del controlador de eventos courseViewer _Load.

  4. En el método del controlador de eventos courseViewer _Load, copie y pegue el código siguiente que define la DataGridView, ejecuta una consulta que devuelve una colección de departamentos (ordenados por Name) y enlaza la colección de objetos Department al control 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);
    }
    

Para mostrar cursos para el departamento seleccionado

  1. En el diseñador de formularios de CourseViewer, haga doble clic en el control departmentList.

    De este modo, se crea método del controlador de eventos departmentList_SelectedIndexChanged.

  2. Pegue el código siguiente que carga los cursos que están relacionados con el departamento seleccionado.

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

Pasos siguientes

Ha creado correctamente consultas que devuelven objetos Department y Course, y los enlazan a los controles. Después, guardará los cambios efectuados en los objetos Course en la cuadrícula de datos de nuevo en la base de datos: Insertar y actualizar datos (Tutorial rápido de Entity Framework).

Vea también

Conceptos

Consultar un modelo conceptual (Entity Framework)
Trabajar con datos de entidad

Otros recursos

Ejemplos (Entity Framework)