[翻译]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)/对象服务(实体框架)

 

作者: 徐少侠
出处: http://www.cnblogs.com/Chinese-xu/

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

分享家:Addthis中文版
标签: 入门, .NET, 编程, EF

本文转自徐少侠博客园博客,原文链接:http://www.cnblogs.com/Chinese-xu/archive/2007/09/29/910481.html,如需转载请自行联系原作者

目录
相关文章
|
7天前
|
数据可视化 网络协议 C#
C#/.NET/.NET Core优秀项目和框架2024年3月简报
公众号每月定期推广和分享的C#/.NET/.NET Core优秀项目和框架(每周至少会推荐两个优秀的项目和框架当然节假日除外),公众号推文中有项目和框架的介绍、功能特点、使用方式以及部分功能截图等(打不开或者打开GitHub很慢的同学可以优先查看公众号推文,文末一定会附带项目和框架源码地址)。注意:排名不分先后,都是十分优秀的开源项目和框架,每周定期更新分享(欢迎关注公众号:追逐时光者,第一时间获取每周精选分享资讯🔔)。
|
25天前
|
开发框架 JavaScript .NET
asp.net中条件查询+分页
asp.net中条件查询+分页
15 1
|
1月前
|
SQL 数据库 C#
C# .NET面试系列十一:数据库SQL查询(附建表语句)
#### 第1题 用一条 SQL 语句 查询出每门课都大于80 分的学生姓名 建表语句: ```sql create table tableA ( name varchar(10), kecheng varchar(10), fenshu int(11) ) DEFAULT CHARSET = 'utf8'; ``` 插入数据 ```sql insert into tableA values ('张三', '语文', 81); insert into tableA values ('张三', '数学', 75); insert into tableA values ('李四',
61 2
C# .NET面试系列十一:数据库SQL查询(附建表语句)
|
25天前
|
开发框架 网络协议 .NET
深入.net框架
深入.net框架
11 0
|
25天前
|
SQL 数据库
使用ADO.NET查询和操作数据
使用ADO.NET查询和操作数据
9 0
|
2月前
|
算法 BI API
C#/.NET/.NET Core优秀项目和框架2024年1月简报
C#/.NET/.NET Core优秀项目和框架2024年1月简报
|
3月前
|
开发框架 前端开发 .NET
ASP.NET CORE 3.1 MVC“指定的网络名不再可用\企图在不存在的网络连接上进行操作”的问题解决过程
ASP.NET CORE 3.1 MVC“指定的网络名不再可用\企图在不存在的网络连接上进行操作”的问题解决过程
38 0
|
26天前
|
开发框架 前端开发 .NET
进入ASP .net mvc的世界
进入ASP .net mvc的世界
25 0
|
26天前
mvc.net分页查询案例——mvc-paper.css
mvc.net分页查询案例——mvc-paper.css
4 0
|
1月前
|
开发框架 前端开发 .NET
C# .NET面试系列六:ASP.NET MVC
<h2>ASP.NET MVC #### 1. MVC 中的 TempData\ViewBag\ViewData 区别? 在ASP.NET MVC中,TempData、ViewBag 和 ViewData 都是用于在控制器和视图之间传递数据的机制,但它们有一些区别。 <b>TempData:</b> 1、生命周期 ```c# TempData 的生命周期是短暂的,数据只在当前请求和下一次请求之间有效。一旦数据被读取,它就会被标记为已读,下一次请求时就会被清除。 ``` 2、用途 ```c# 主要用于在两个动作之间传递数据,例如在一个动作中设置 TempData,然后在重定向到另
95 5