Free Hit Counters
http://www.dellasdeals.com

[翻译]ADO.NET Entity Framework Beta2(九)/快速入门(实体框架)(4)/查询实体及关系

This is the final task of the Entity Framework Quickstart. In this task, you will create strongly-typed queries against the CLR objects that represent entities and associations in the School model, and bind display controls to the object collections returned from these queries. You will also run the completed ClassSchedule application.

本任务是 实体框架快速入门的最后一个任务。在本任务中,你将创建强类型的基于CLR对象的查询来展现学校数据库内的实体和关系,并且将显示控件绑定到由这些查询所返回的对象集合。最后你能完整的来运行ClassSchedule应用程序。

To query the students in the School database/查询学校数据库内的学生

  1. At the beginning of the code file for the StudentSchedule form, add the following using (C#) or Imports (Visual Basic) statements to reference the model created from the School database and the entity namespace.
    在StudentSchedule窗体的代码开头,按照使用的语言不同,添加以下引用声明以引用学生数据库和实体命名空间内的模型。

    Visual Basic
    Imports SchoolModel
    Imports System.Data.Objects
    C#
    using System.Data.Objects;
    using SchoolModel;
  2. At the top of the partial class definition for the StudentSchedule form, add the following code that creates an ObjectContext instance.
    在StudentSchedule窗体的部分类定义开头,添加以下代码以创建一个实体关联对象(ObjectContext)的实例

    Visual Basic
    ' Create an ObjectContext instance based on SchoolEntity.
    ' 基于学校实体创建一个实体关联对象
    Private schoolContext As SchoolEntities
    C#
    // Create an ObjectContext instance based on SchoolEntity.
    // 基于学校实体创建一个实体关联对象
    private SchoolEntities schoolContext;
  3. In the StudentSchedule form designer, double-click the StudentSchedule form.
    在StudentSchedule窗体的设计界面,双击窗体。

    This opens the code page for the form and creates the studentSchedule_Load event handler method.
    开发环境将自动转到代码设计窗体,并自动创建studentSchedule_Load事件处理程序。

  4. In the studentSchedule_Load event handler method, copy and paste the following code that defines the DataGridView, executes a query that returns a collection of students (ordered by LastName), and binds the collection of Person objects to the studentList control.
    在studentSchedule_Load事件处理程序内,复制并粘贴以下代码以定义DataGridView控件的外观、执行一个返回学生集合(按LastName排序)的查询,以及将人的集合对象绑定到studentList控件

    Visual Basic
    ' Initialize the ObjectContext.
    ' 初始化实体关联对象
    schoolContext = New SchoolEntities()

    ' Define the DataGridView.
    ' 定义DataGridView
    studentClasses.Columns.Add("courseName", "Course Name")
    studentClasses.Columns.Add("courseDate", "Date Completed")
    studentClasses.Columns.Add("courseGrade", "Grade")
    studentClasses.Columns.Add("courseCredits", "Credits")

    ' Get students as all people who have enrollment dates.
    ' 获得所有拥有入学日期的学生作为全体集合
    Dim students As ObjectQuery(Of Person) = _
    schoolContext.Person.Where( _
    "it.EnrollmentDate IS NOT NULL").OrderBy("it.LastName")

    ' Define the query path for queries that return a Person object
    'and bind the ComboBox to the collection returned by the query.
    ' 为查询定义查询路径以返回一个Person对象
    '然后将ComboBox控件绑定到查询所返回的集合上
    Me.studentsList.DataSource = students.Include("Enrollment.Course")
    Me.studentsList.DisplayMember = "LastName"
    C#
    // Initialize the ObjectContext.
    //初始化实体关联对象
    schoolContext = new SchoolEntities();

    // Define the DataGridView.
    // 定义DataGridView
    studentClasses.Columns.Add("courseName", "Course Name");
    studentClasses.Columns.Add("courseDate", "Date Completed");
    studentClasses.Columns.Add("courseGrade", "Grade");
    studentClasses.Columns.Add("courseCredits", "Credits");

    // Get students as all people who have enrollment dates.
    // 获得所有拥有入学日期的学生作为全体集合
    ObjectQuery<Person> students = schoolContext.Person.Where(
    "it.EnrollmentDate IS NOT NULL").OrderBy("it.LastName");

    // Define the query path for queries that return a Person object
    // and bind the ComboBox to the collection returned by the query.
    // 为查询定义查询路径以返回一个Person对象

    // 然后将ComboBox控件绑定到查询所返回的集合上
    this.studentsList.DataSource = students.Include("Enrollment.Course");
    this.studentsList.DisplayMember = "LastName";

To display classes for the selected student /显示被选中学生的课程情况

  1. In the StudentSchedule form designer, double-click the studentsList control.
    在StudentSchedule窗体的设计界面,双击studentsList控件

    This creates the studentsList_SelectedIndexChanged event handler method.
    将自动创建studentsList_SelectedIndexChanged事件处理程序

  2. Paste the following code that loads the courses that are related to the selected student.
    粘贴以下代码.这些代码将按照选中的学生加载相关的课程信息

    Visual Basic
    Try
    ' clear existing rows from the DataGridView.
    ' 将DataGridView内的现有行清空
    studentClasses.Rows.Clear()

    ' Get the Person object for the selected student.
    ' 获取被选中的学生对象
    Dim student As Person = CType(studentsList.SelectedItem, Person)

    Dim enrollment As Enrollment
    For Each enrollment In student.Enrollment
    ' Create an array of row cells.
    ' 创建一个单元格数组作为行
    Dim row() As Object = New Object(4) {}

    ' Load object values from entities.
    ' 获取实体的各种值
    row(0) = enrollment.Course.Title
    row(1) = enrollment.Course.EndDate
    row(2) = enrollment.Grade
    row(3) = enrollment.Course.Credits

    ' Add the new row to the DataGridView.
    ' 将新行添加到DataGridView
    studentClasses.Rows.Add(row)
    studentClasses.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells)
    Next
    Catch ex As Exception
    MessageBox.Show(ex.Message)
    End Try
    C#
    try
    {
    // clear existing rows from the DataGridView.

    // 将DataGridView内的现有行清空
    studentClasses.Rows.Clear();

    // Get the Person object for the selected student.
    // 获取被选中的学生对象
    Person student = (Person)studentsList.SelectedItem;

    foreach (Enrollment enrollment in student.Enrollment)
    {
    // Create an array of row cells.
    // 创建一个单元格数组作为行
    object[] row = new object[4];

    // Load object values from entities.
    // 获取实体的各种值
    row[0] = enrollment.Course.Title;
    row[1] = enrollment.Course.EndDate;
    row[2] = enrollment.Grade;
    row[3] = enrollment.Course.Credits;

    // Add the new row to the DataGridView.
    // 将新行添加到DataGridView
    studentClasses.Rows.Add(row);
    studentClasses.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
    }
    }
    catch (Exception ex)
    {
    MessageBox.Show(ex.Message);
    }

To close connections by disposing the long-running object context
释放实体关联对象以关闭连接

  • In the closeForm_Click event handler method, type the following code. This code disposes of the object context before the form is closed.
    closeForm_Click事件处理方法内,键入以下代码。这些代码将在窗体关闭之前释放实体关联对象。

    Visual Basic
    ' Dispose the object context.
    ' 释放实体关联对象
    schoolContext.Dispose()
    C#
    // Dispose the object context.
    // 释放实体关联对象
    schoolContext.Dispose();

To build and run the Class Scheduling application/编译与运行ClassScheduing应用程序

  1. From the Debug menu, select Start Debugging or Start Without Debugging.
    调试菜单,选择启动调试直接运行
    (需要在程序代码的开头额外附加如下两个名字空间的引用,否则会有错误提示.)
    using SchoolModel;
    using System.Data.Objects;

    This builds and starts the application.
    这个步骤将编译并运行应用程序

  2. When the form loads, select a student from the ComboBox control by last name.
    当窗体加载后,在组合框内选择一个学生的名字.

    This displays the courses that the student is taking.
    将在表格内显示该学生关联的课程

Next Steps/下一步

You have successfully created and run the Class Schedule application. You have also completed this Entity Framework quickstart. For more information about the Entity Framework, see the other topics in Object Services (Entity Framework).
你已经成功的创建并运行了ClassSchedule应用程序.

See Also/请参见

Concepts/概念

Working with Entity Data/使用实体数据工作

Other Resources/其他资源

Samples (Entity Framework)/样例(实体框架)
Object Services (Entity Framework)/对象服务(实体框架)

 

posted @ 2007-09-29 11:31  徐少侠  阅读(2643)  评论(8编辑  收藏  举报
作者:徐少侠 出处:http://www.cnblogs.com/Chinese-xu/

本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,如有问题,可以通过 Chinese_Xu@126.com 联系我,非常感谢。