使用ADO.NET Entity Framework
的实体作为数据源Data Source(附Demo程序下载)- 系列3
本文是
ADO.NET Entity Framework
系列文章第三篇,继续演示如何使用ADO.NET Entity Framework 的实体作为数据控件的数据源Data Source,轻松将数据记录显示在数据控件中。
ADO.NET Entity Framework 前两篇文章如下:
首先,根据ADO.NET Entity Data Model 向导创建EDM文件,具体可以参考《
ADO.NET Entity Framework 入门示例向导(附Demo程序下载)》文章。
1.
增加New Data Source
操作步骤如下:
选择Add New Data Source,弹出Data Source Configuration Wizard 窗口,界面如下:
选择Object 作为Data Source Type,然后点击Next按钮。
在向导的下一页,展开树节点 – Data Model,显示所有的Entity 类。选择需要创建Data Source 的 Entity 类,然后点击Next 按钮。
2.
显示Data Source
选择Data 菜单 / Show Data Sources 菜单项,显示项目中的Data Sources。
3.
将上一步创建的Data Source
拖曳到Windows Form
窗体上。
默认情况下,一个新的DataGridView 控件和Navigation toolbar 控件自动添加到Windows Form窗体上。同时,也自动创建BindingSource 和Binding Navigation 控件,并且上述的两个控件与BindingSource 和Binding Navigation 控件进行了自动绑定。
界面如下:
4.
下面进一步在DataGridView
控件显示Data Source
的数据。
在Windows Form 添加如下代码:
private void Form1_Load(object sender, EventArgs e)
{
NorthwindEntities northwindEntities = new NorthwindEntities();
customersBindingSource.DataSource = northwindEntities.Customers;
}
5.
编辑和保存数据
BindingSource 组件确保对DataGridView 控件的编辑更新到Entity Class。当用户完成编辑后,需要保存更新的数据到数据库中。
下一步,将 Navigation toolbar 工具栏的Save 的Enable的属性调整为True。双击Save按钮,在Save 的click 事件添加如下代码:
private void customersBindingNavigatorSaveItem_Click(object sender, EventArgs e)
{
northwindEntities.SaveChanges();
}
SaveChanges() 方法负责将Entity class 的更新保存到数据库中。